JavaScript: Uncurry a function up to depth n
JavaScript fundamental (ES6 Syntax): Exercise-114 with Solution
Write a JavaScript program to uncurry a function up to depth n.
- Return a variadic function.
- Use Array.prototype.reduce() on the provided arguments to call each subsequent curry level of the function.
- If the length of the provided arguments is less than n throw an error.
- Otherwise, call fn with the proper amount of arguments, using Array.prototype.slice(0, n).
- Omit the second argument, n, to uncurry up to depth 1.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const uncurry = (fn, n = 1) => (...args) => {
const next = acc => args => args.reduce((x, y) => x(y), acc);
if (n > args.length) throw new RangeError('Arguments too few!');
return next(fn)(args.slice(0, n));
};
const add = x => y => z => x + y + z;
const uncurriedAdd = uncurry(add, 3);
console.log(uncurriedAdd(1, 2, 3));
Sample Output:
6
Pictorial Presentation:
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-114-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to unescape escaped HTML characters.
Next: Write a JavaScript program to create a function that accepts up to one argument, ignoring any additional arguments.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join