Skip to content
Advertisement

Is this the correct recursive way to write curry function?

I can’t understand if this recursive curry function is correct or not.

function curry(fn) {
  return function curryInner(...args) {
    if (args.length >= fn.length) return fn(...args);
    return function (...next) {
      return curryInner(...args, ...next);
    };
  };
}

const example = {
  multiplier: 5,
  calculate: function (a, b) {
    return (a + b) * this.multiplier;
  },
};
example.curriedVersion = curry(example.calculate);

console.log(example.calculate(1, 2));
console.log(example.curriedVersion(1)(2));

I have curry function implement with binding but I am not sure why it works and recursive does not. Can you help me to understand this, I think my context understanding in this functions is incorrect

function curry(func) {
    return function curried(...args) {

        if (args.length >= func.length) {
            return func.apply(this, args)
        } else {
            return curried.bind(this, ...args)
        }
    }
}

Advertisement

Answer

Your curring is correct, the problem is with this.multiplier.

When you use the expression example.calculate without calling the function, it doesn’t bind this. So this.multiplier will be undefined.

Use example.calculate.bind(example) and your currying will work as expected.

function curry(fn) {
  return function curryInner(...args) {
    if (args.length >= fn.length) return fn(...args);
    return function (...next) {
      return curryInner(...args, ...next);
    };
  };
}

const example = {
  multiplier: 5,
  calculate: function (a, b) {
    return (a + b) * this.multiplier;
  },
};
example.curriedVersion = curry(example.calculate.bind(example));

console.log(example.calculate(1, 2));
console.log(example.curriedVersion(1)(2));
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement