Hacker News new | ask | show | jobs
by jfaucett 3901 days ago
"Chaining or nesting a series of function calls, depending on the language, can be more readable still than the variables approach and at the same time more concise".

Couldnt agree more, variables are just clutter you have to keep mental track of, and working with series of transformations is much easier (for me at least) to process. I would be interested to know if its like this for all developers, perhaps not, since I know some that are also opposed to recursion.

but for me this:

    sum([]) = 0.
    sum([H|T]) = H + sum(T).
is much easier to understand than:

    function sum(ary) {
      var i = ary.length,
       res;
      while(--i) {
        res += ary[i];
      }
      return res;
    }
2 comments

    function sum(array) {
      return array.reduce((a, b) => a + b);
    }
With a loop:

    function sum(array) {
      let acc = 0;
      for(let val of array) {
        acc += val;
      }
      return acc;
    }
What's the value of sum for an empty array in your example?
The reduce one needs an initial value of 0 for that to work. Then both versions will return 0 if the array is empty.

    array.reduce((a, b) => a + b, 0);

    sum = (values) ->
      values.reduce (result, x) -> result + x