Hello friends, in this article I'm going to discuss and walk through my thought process of solving the Implement curry()
problem on BFE.dev.
Here's the question.
Q. 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'
Here's the Solution:
/**
* @param { (...args: any[]) => any } fn
* @returns { (...args: any[]) => any }
*/
function curry(fn) {
return function curried(...args){
// Check if the `fn` passed have enough args or not
if(args.length >= fn.length){
// If there are enough args call the `fn` with the `args`
return fn.apply(this, args)
}
else{
// Else bind the function with the remaining args and recursively return it.
return curried.bind(this, ...args)
}
}
}
Conclusion
Thanks for going through the problem, I'll be adding more problems in the blog as I continue to practice, feel free to like, share & comment your feedback.