I am trying to understand why this piece of code does not work when I was trying to implement the curry function in JavaScript.
When I run the following piece of code, it prints undefined:
function curry(func) {
return function curried(...args) {
if (args.length >= func.length) {
return func.apply(this, args)
}
return (arg) => {
arg === undefined ? curried.apply(this, args) : curried.apply(this, [...args, arg])
}
}
}
const mul = (a, b) => a * b;
const curried = curry(mul);
console.log(curried(7)(3)) // undefined
However, once I remove the brackets in the return statement it now works:
function curry(func) {
return function curried(...args) {
if (args.length >= func.length) {
return func.apply(this, args)
}
return (arg) => arg === undefined ? curried.apply(this, args) : curried.apply(this, [...args, arg]) // Brackets removed here
}
}
const mul = (a, b) => a * b;
const curried = curry(mul);
console.log(curried(7)(3)) // 21
Anyone knows why this is the case?