serendipityApe / javascriptPromotion

资深前端必备的编码问题
3 stars 0 forks source link

create a sum() #23

Open serendipityApe opened 2 years ago

serendipityApe commented 2 years ago

https://bigfrontend.dev/problem/create-a-sum

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 // true

answer:

function sum(num) {
  // your code here
  const func = (num2) =>{
    return sum(num+num2)
  }
  func.valueOf = () => num;
  return func;
}

other: func.valueOf will be triggered before we want to change func's type example: a == b if typeof a differents with typeof b,js will change typeofa to typeof b,and js will implicitly call a.valueOf(),but if a === b,typeof a will not be converted; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf