“add” function that works with different combinations of chaining/arguments

前端 未结 4 1855
忘掉有多难
忘掉有多难 2020-11-28 13:09

I\'m trying to write an add function that will work in many scenarios.

add(2,2,2) //6
add(2,2,2,2) //8
add(2)(2)(2) // 6
add(2)(2)(2,2).value() //8
add(2,2)(         


        
4条回答
  •  青春惊慌失措
    2020-11-28 13:29

    Also they need to always return ints (not strings), and it seems like sometimes they do and other times they don't?

    Yeah, this is definitely a conceptual problem. These two things you want aren't compatible. Is add(2,2,2) a number or something with an add method?

    add(2,2,2) //6
    add(2,2,2).add(2).value() //8
    

    Even if there is a fancy way to add methods to nubmers, I would highly recommend keeping things simple and always requiring a ".value()" call to end the chain. This way all calls to ".add" return an "adder object" and all calls to ".value" return a regular number.

    it seems like I would have to keep nesting the add functions if I wanted to chain more than two together and also add the value function to each of them, but obviously I'm missing something simple that will allow me to chain them as much as I like, and call value on any of them.

    The answer to this is to use recursive functions. Here is a function that creates the "adder" object I mentioned previously:

    function sumArray(arr){
        var s = 0;
        for(var i=0; i

    Then your initial add function would look like this:

    function add(/**/){
        return mkAdder(sumArray(arguments));
    }
    

提交回复
热议问题