Spread element magically turns functions into 'not functions'

前端 未结 4 912
北恋
北恋 2021-01-07 23:37

Suppose I have this simple JavaScript function:

function returnArray(){
    return [1, 2, 3];
}

Further suppose that I then say

<         


        
4条回答
  •  长情又很酷
    2021-01-08 00:21

    Your logical error has been pointed out in comments and answers, but let me point out a cleaner, simpler, less bug-prone way to write this which is more in line with basic principles of recursion.

    function double([head, ...tail]) {
      if (head === undefined) return [];
      return [2*head, ...double(tail)];
    }
    

    In other words, there is only one "base case", namely the empty array, which returns an empty array. Everything else is simple recursion.

    You could "functionalize" this further with

    function map(fn) {
      return function iter([head, ...tail]) {
        return head === undefined ? [] : [fn(head), ...iter(tail)];
      };
    }
    
    const double = map(x => 2*x);
    console.log(double([1, 2, 3]));
    

提交回复
热议问题