Question Bank
JavaScript Add-N via Currying: Two Approaches Quiz
Difficulty: Medium
Two seeded ways to build an `adder(n)` that adds `n` to its argument (closure-returning-function and `Function.prototype.bind`), plus two companions on three-arg currying and a generic curry helper.
JavaScript Add-N via Currying: Two Approaches Quiz
Two seeded ways to build an `adder(n)` that adds `n` to its argument (closure-returning-function and `Function.prototype.bind`), plus two companions on three-arg currying and a generic curry helper.
629 views
16
Implement adder(n) so it returns a function that adds n to its argument. Use the classic closure-returning-function pattern.
Examples
Example 1:
Input:
const adder5 = adder(5);
console.log(adder5(3));
console.log(adder(5)(3));
Output:
8
8
Explanation: adder(5) captures n = 5 in a closure and returns a function that adds 5 to whatever it receives.Implement adder(n) using Function.prototype.bind to partially apply a binary add(a, b) function. The this binding should be null.
Examples
Example 1:
Input:
const adder5 = adder(5);
console.log(adder5(3));
Output: 8
Explanation: bind(null, 5) fixes the first argument of add to 5, so the returned function adds 5 to its remaining input.Extend the closure pattern to a three-argument curried sum: sum(a)(b)(c) should return a + b + c. Show that any prefix returns a function ready for the next argument.
Examples
Example 1:
Input: sum(1)(2)(3)
Output: 6
Explanation: each call captures one argument and returns the next function in the chain.Write a generic curry(fn) helper that takes a function of fixed arity and returns a curried version: each call either fills another argument and returns a curried continuation, or invokes the original function once enough arguments have arrived.
Examples
Example 1:
Input:
const curriedAdd3 = curry((a, b, c) => a + b + c);
console.log(curriedAdd3(1)(2)(3));
console.log(curriedAdd3(1, 2)(3));
console.log(curriedAdd3(1)(2, 3));
console.log(curriedAdd3(1, 2, 3));
Output:
6
6
6
6
Explanation: a generic curry helper accepts any partition of the original arguments and only invokes the wrapped function once fn.length is satisfied.