eslint-plugin-functional icon indicating copy to clipboard operation
eslint-plugin-functional copied to clipboard

New rule: no partial array reduce

Open danielnixon opened this issue 1 year ago • 3 comments

Suggestion

A new rule that forbids the partial versions of reduce and reduceRight.

Given:

  const arr: readonly string[] = ...; // may or may not be empty

Would be invalid according to suggested rule:

  // compiles, throws TypeError: Reduce of empty array with no initial value
  const foo = arr.reduce((a, b) => a);

  // compiles, throws TypeError: Reduce of empty array with no initial value
  const bar = arr.reduceRight((a, b) => a);

Would be valid according to suggested rule:

  // compiles, doesn't throw
  const foo = arr.reduce((a, b) => a + b, "");

  // compiles, doesn't throw
  const bar = arr.reduceRight((a, b) => a + b, "");


  // if you can prove to tsc that you have at least one element, the form without `initialValue` is safe:
  const arr: readonly [string, ...(readonly string[])] = [""];
  const foo = arr.reduce((a, b) => a);

This is equivalent to the situation with reduce versus fold in Scala: https://www.wartremover.org/doc/warts.html#iterableops

danielnixon avatar Feb 05 '23 08:02 danielnixon