JavaScript: Uncurry a function up to depth n
JavaScript fundamental (ES6 Syntax): Exercise-114 with Solution
Uncurry Function to Depth n
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
// Define the 'uncurry' function.
const uncurry = (fn, n = 1) => (...args) => {
// Define a helper function 'next' that applies functions sequentially.
const next = acc => args => args.reduce((x, y) => x(y), acc);
// Check if the number of arguments is sufficient.
if (n > args.length) throw new RangeError('Arguments too few!');
// Apply 'fn' partially with the first 'n' arguments and return the resulting function.
return next(fn)(args.slice(0, n));
};
// Define a curried addition function.
const add = x => y => z => x + y + z;
// Uncurry the 'add' function to accept three arguments.
const uncurriedAdd = uncurry(add, 3);
// Test the uncurried addition function with three arguments.
console.log(uncurriedAdd(1, 2, 3));
// Output: 6
Output:
6
Visual 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 and Language Statistics
- Weekly Trends and Language Statistics