logoalt Hacker News

franeytoday at 6:51 PM3 repliesview on HN

At least in TypeScript, it's a bit clunky to type, and I usually forget the order of the reduce function's arguments (accumulator, current item). Maybe it's just me, but it's especially easy to forget the order when the position of the accumulator is the 1st argument to the callback but the 2nd argument of the reduce function:

    array.reduce(
      (accumulator, currentItem) => {...},
      initialValue,
    )
In .filter(), The current item is the 1st argument and the intermediate/accumulated value comes later: filter((currentItem, index, intermediateArray)) => ...)

I use .filter() more often, so that argument ordering where currentItem is right next to the array is more intuitive for me


Replies

yojotoday at 7:15 PM

In TS/JS you’re usually inlining the reducer fn, and there’s something hard to read/especially ugly about the comma after the bracket or arrow fn into the initalValue.

That said, when I’m reducing a list, I still use reduce.

BariumBluetoday at 7:12 PM

It literally may be a syntax thing, but I too can never remember the exact arguments to put where so I never use it.

I think if `reduce` looked more functional or more like Erlang code, it'd be easier to read and digest.

chrisandchristoday at 7:10 PM

> accumulator

I had similar trouble, but I know call the "accumulator" just "previous" which makes it more logical in my head:

.reduce( (previous, current) => previous+current, 0 );

show 1 reply