Skip to content

Latest commit

 

History

History
61 lines (44 loc) · 1.28 KB

File metadata and controls

61 lines (44 loc) · 1.28 KB

1. implement curry()

Problem

https://bigfrontend.dev/problem/implement-curry

Problem Description

Currying is a useful technique used in JavaScript applications.

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

Here is an example

const join = (a, b, c) => {
  return `${a}_${b}_${c}`;
};

const curriedJoin = curry(join);

curriedJoin(1, 2, 3); // '1_2_3'

curriedJoin(1)(2, 3); // '1_2_3'

curriedJoin(1, 2)(3); // '1_2_3'

more to read

https://javascript.info/currying-partials https://lodash.com/docs/4.17.15#curry

Solution

/**
 * @param { Function } func
 */
function curry(func) {
  // Return a wrapper function to make it curry-able.
  return function curried(...args) {
    // If passed arguments count is greater than or equal to original function 'func'
    // parameters count, directly call 'func' with passed arguments.
    if (args.length >= func.length) {
      return func.apply(this, args);
    } else {
      // Otherwise return another wrapper function to gather new argument
      // and pass it to `curried` function. This will continue until
      // arguments count >= parameters count.
      return function (...args2) {
        return curried.apply(this, args.concat(args2));
      };
    }
  };
}