I can’t understand if this recursive curry function is correct or not.
JavaScript
x
19
19
1
function curry(fn) {
2
return function curryInner(args) {
3
if (args.length >= fn.length) return fn(args);
4
return function (next) {
5
return curryInner(args, next);
6
};
7
};
8
}
9
10
const example = {
11
multiplier: 5,
12
calculate: function (a, b) {
13
return (a + b) * this.multiplier;
14
},
15
};
16
example.curriedVersion = curry(example.calculate);
17
18
console.log(example.calculate(1, 2));
19
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
JavaScript
1
11
11
1
function curry(func) {
2
return function curried(args) {
3
4
if (args.length >= func.length) {
5
return func.apply(this, args)
6
} else {
7
return curried.bind(this, args)
8
}
9
}
10
}
11
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.
JavaScript
1
19
19
1
function curry(fn) {
2
return function curryInner(args) {
3
if (args.length >= fn.length) return fn(args);
4
return function (next) {
5
return curryInner(args, next);
6
};
7
};
8
}
9
10
const example = {
11
multiplier: 5,
12
calculate: function (a, b) {
13
return (a + b) * this.multiplier;
14
},
15
};
16
example.curriedVersion = curry(example.calculate.bind(example));
17
18
console.log(example.calculate(1, 2));
19
console.log(example.curriedVersion(1)(2));