False Positive Array.reduce()

  • What language is this for?
    Typescript
  • Which rule?
    RSPEC-6959 “Array.reduce()” calls should include an initial value
  • Why do you believe it’s a false-positive/false-negative?
    I believe this is a harmful recommendation as following the advice, (adding in an initial value) changes the behaviour of the code significantly when performing certain operations. Any operation that behaves differently based on the number of elements in the array, eg. string concatenation, will be incorrect.

My supplied code is a perfect example, it is a simple string concatenation with a separator character. Supplying an initial value results in extra separator characters added to the string, which breaks the parsing of the value in other systems. Not only is this not the intended behaviour, the actual behaviour is not obvious for anyone reading the code.

It is far more readable to explicitly check the length of the array and adjust behaviour accordingly with an if statement.

  • Are you using

    • SonarCloud
  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)
    The below typescript code will fail RSPEC-6959, but should not as it would be impossible for reduce() to throw a TypeError, given the type checking on the function and the explicit length check right before the call to array.reduce().

export function flattenStringArray(stringsToConcat: string[], separator: string): string {
  if (!stringsToConcat || stringsToConcat.length === 0) {
    return '';
  }
  return stringsToConcat.reduce((current, next) => `${current}${separator}${next}`);
}

Hi @mon0051,

Thanks a lot for your valuable feedback, and welcome to SonarSource community.

If I understand you perfectly, you think that forcing the provision of an initial value to Array.reduce may lead to some unintended results - or at least different results compared to not providing an initial value. This is a very interesting point.

I understand that your code sample is rhetorical, which is perfectly valid to demonstrate that passing or not passing an initial value may lead to different results. Do you have some practical examples or patterns in mind that are negatively impacted by the current rule implementation?

Eric.

1 Like