BFE.dev | 23. create a sum() | JavaScript Problem Solving

Hello friends, in this article I'm going to discuss and walk through my thought process of solving the create a sum() problem on BFE.dev.

problem link

Here's the question

Create a sum(), which makes the following possible

const sum1 = sum(1)
sum1(2) == 3 // true
sum1(3) == 4 // true
sum(1)(2)(3) == 6 // true
sum(5)(-1)(2) == 6 // true

Here's the Solution


/**
 * @param {number} num
 */

function sum(num) {

 // create a recursive function to call `sum()` with argument
   const func = function(num2){
    return sum(num + num2) // return the recursive function
  }

  // assign `valueOf` so that the function can be compared with the number
  func.valueOf = () => num;

 // return the func 
  return func
}

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.