DEV Community

Cover image for Javascript Currying #1
chandra penugonda
chandra penugonda

Posted on • Edited on

Javascript Currying #1

Currying is a useful technique used in JavaScript applications.

Please implement a curry() function, which accepts a function and return a curried one.

Good morning! Here's your coding interview problem for today.

This problem was asked by Google.

Currying is a useful technique used in JavaScript applications.

Please implement a curry() function, which accepts a function and return a curried one.

Example

const multiplyThree = (a, b, c) => { return a * b * c; }; const curriedMultiplyThree = curry(multiplyThree); console.log(curriedMultiplyThree(1, 3, 5)); // 15 console.log(curriedMultiplyThree(1, 2)(5)); // 10 console.log(curriedMultiplyThree(1)(2)(3)); // 6 
Enter fullscreen mode Exit fullscreen mode

Note: The implementation of curry() is not provided and needs to be completed.

Solution

function curry(fn) { return function curried(...args) { if (fn.length === args.length) { return fn.apply(this, args); } return (...args2) => curried.apply(this, args.concat(args2)); }; } 
Enter fullscreen mode Exit fullscreen mode

Explanation

  • When you call curry() and pass it a function, it returns a new curried() function.
  • The first time you call curried() and pass it some arguments, it checks if the number of arguments matches the required arguments for the original function.
  • If it does match, it calls the original function with those arguments.
  • If it doesn't match, it returns a new function that will accumulate more arguments and call curried() again.
  • This continues until enough arguments have been accumulated to call the original function.

Top comments (0)