DEV Community

jser
jser

Posted on • Updated on

BFE.dev #23. create a sum()

https://bfe.dev is like a LeetCode for FrontEnd developers. I’m using it to practice my skills.

Alt Text

This article is about the coding problem BFE.dev#23. create a sum()

problem

Create a sum(), which makes 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 
Enter fullscreen mode Exit fullscreen mode

analysis

From above requirements, obviously

  1. sum() should return a function, which takes in one new argument
  2. sum() sums up all the arguments passed, and repeat 1
  3. A function could equal to a number with == not ===, by type coercion, we could use valueOf or toString to accomplish.

Let's code

First we handle the function returning part. Above 1 and 2 tells us that we need to accumulate the arguments, which could be treated as the second argument

function sum(num, currentSum = 0) {
  const newCurrentSum = num + currentSum

  const func = function(arg) {
    return sum(arg, num + currentSum)
  }

  return func
}

Enter fullscreen mode Exit fullscreen mode

At last, let's define the valueOf.

function sum(num, currentSum = 0) {
  const newCurrentSum = num + currentSum

  const func = function(arg) {
    return sum(arg, num + currentSum)
  }

  func.valueOf = () => newCurrentSum
  // below also works
  // func.toString = () => newCurrentSum.toString()

  return func
}
Enter fullscreen mode Exit fullscreen mode

OK, passed

Alt Text

Interested to try by yourself? Have a try at BFE.dev https://bigfrontend.dev/problem/create-a-sum

Top comments (0)