Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)
        }
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading