Typescript-eslint: Rule proposal: Only allow `Array#reduce()` for summing/multiplying numbers

Created on 25 Feb 2019  路  1Comment  路  Source: typescript-eslint/typescript-eslint

Array#reduce() can often make code less readable and sometimes also slower. A for-of loop is usually a better choice.

See this Twitter thread: https://twitter.com/sophiebits/status/1099014182261776384?s=21

Not sure how strict we should/can be, but my thinking is that we only allow Array#reduce() when the callback returns a number and the initialValue is a number if set.

new plugin rule eslint-plugin

Most helpful comment

I don't necessarily agree with this.

The reduce function is a boundary. Mutating the accumulator within that boundary is fine from a purity standpoint, as long as the initialValue isn't a variable reference.

arr.reduce((acc, value) => {
    acc[calcdKey] = value;
    return acc;
}, {});

The thing I'd lint would be:
Ensuring that the initial value is not a variable reference (unless the variable's type is number | string | boolean).

>All comments

I don't necessarily agree with this.

The reduce function is a boundary. Mutating the accumulator within that boundary is fine from a purity standpoint, as long as the initialValue isn't a variable reference.

arr.reduce((acc, value) => {
    acc[calcdKey] = value;
    return acc;
}, {});

The thing I'd lint would be:
Ensuring that the initial value is not a variable reference (unless the variable's type is number | string | boolean).

Was this page helpful?
0 / 5 - 0 ratings

Related issues

golopot picture golopot  路  3Comments

kmdrGroch picture kmdrGroch  路  3Comments

bradzacher picture bradzacher  路  3Comments

jwldnr picture jwldnr  路  3Comments

Zjaaspoer picture Zjaaspoer  路  3Comments