https://bfe.dev is like a LeetCode for FrontEnd developers. I’m using it to practice my skills.
This article is about the coding problem #1 implement curry()
First let’s decide the input and output of our function from the examples.
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'
Obviously curry() should return a function, which accepts arbitrary arguments, and do the following:
- if arguments are enough, call join and return the result
 - if not enough, then return a new function which does 1. Key is above point 2.
 
curriedJoin(1,2) should return a new function, which will insert 1,2 before the argument 3 , this could be done by Function.prototype.bind()
function curry(func) {
  return function curried(...args) {
    // 1. if enough args, call func 
    // 2. if not enough, bind the args and wait for new one
    if (args.length >= func.length) {
      return func.apply(this, args)
    } else {
      return curried.bind(this, ...args)
    }
  }
}
Ok, passed!
Hope it helps. See you next time.


    
Top comments (0)