- 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}`);
}