Currying function with unknown arguments in JavaScript

后端 未结 2 397
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 07:13

In a recent interview, I was asked to write a function that adds numbers and accepts parameters like this:

add(1)(2)(3) // result is 6
add(1,2)(3,4)(5) // re         


        
2条回答
  •  Happy的楠姐
    2020-12-17 08:03

    I'm a bit late to the party, but something like this would work (a bit hacky though in my opinion):

    const add = (a, ...restA) => {
      const fn = (b, ...restB) => {
        return add([a, ...restA].reduce((x, y) => x + y) + [b, ...restB].reduce((x, y) => x + y))
      };
      fn.valueOf = () => {
        return [a, ...restA].reduce((x, y) => x + y)
      };
      return fn;
    }
    

    This function returns a function with a value of the sum. The tests below are outputing the coerced values instead of the actual functions.

    console.log(+add(1,2)(3,4)(5)); // 15
    console.log(+add(1)) // 1
    console.log(+add(1)(2)) // 3
    console.log(+add(1)(2)(3)) // 6
    console.log(+add(1)(2)(3)(4)) // 10
    

    Since it's a currying function, it will always return another function so you can do something like this:

    const addTwo = add(2);
    console.log(+addTwo(5)); // 7
    

提交回复
热议问题