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 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
analysis
From above requirements, obviously
-
sum()
should return a function, which takes in one new argument -
sum()
sums up all the arguments passed, and repeat 1 - A function could equal to a number with
==
not===
, by type coercion, we could usevalueOf
ortoString
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
}
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
}
OK, passed
Interested to try by yourself? Have a try at BFE.dev https://bigfrontend.dev/problem/create-a-sum
Top comments (0)