Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rule proposal: require-reduce-initial-value #2454

Closed
zanminkian opened this issue Sep 17, 2024 · 1 comment
Closed

Rule proposal: require-reduce-initial-value #2454

zanminkian opened this issue Sep 17, 2024 · 1 comment

Comments

@zanminkian
Copy link
Contributor

zanminkian commented Sep 17, 2024

Description

If an array is empty, calling reduce/reduceRight method will cause runtime error. We need a rule to force passing initial value to reduce/reduceRight method

const nums: number[] = [];
const sum = nums.reduce((result, num) => result + num); // This will cause runtime error

Fail

[].reduce((a, b)=>a+b);
[].reduceRight((a, b)=>a+b);
someArray.reduce((a, b)=>a+b);
someArray.reduceRight((a, b)=>a+b);

Pass

[].reduce((a, b)=>a+b,0);
[].reduceRight((a, b)=>a+b,foo);
someArray.reduce((a, b)=>a+b, 0);
someArray.reduceRight((a, b)=>a+b, foo);
Array.prototype.reduce.call(nums, (x,y)=>x+y);
Array.prototype.reduce.appy(nums, [(x,y)=>x+y]);

Proposed rule name

require-reduce-initial-value

Additional Info

No response

@sindresorhus
Copy link
Owner

This could be part of #1356

@zanminkian zanminkian closed this as not planned Won't fix, can't repro, duplicate, stale Sep 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants