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

Init argument should be optional in Array.reduce #248

Open
glennsl opened this issue Nov 23, 2024 · 0 comments
Open

Init argument should be optional in Array.reduce #248

glennsl opened this issue Nov 23, 2024 · 0 comments

Comments

@glennsl
Copy link
Contributor

glennsl commented Nov 23, 2024

In JS, the initial value is optional, and if omitted will be taken from the first element of the array. Unfortunately this changes the type of the function, since the initial value needs to be constrained by the element type, and therefore requires a second set of bindings.

From MDN:

initialValue Optional
A value to which accumulator is initialized the first time the callback is called. If initialValue is specified, callbackFn starts executing with the first value in the array as currentValue. If initialValue is not specified, accumulator is initialized to the first value in the array, and callbackFn starts executing with the second value in the array as currentValue. In this case, if the array is empty (so that there's no first value to return as accumulator), an error is thrown.

The first problem then is what to name these bindings. Typically, the operation without an initial value is called reduce and with an initial value is called fold. That's one option, but would be a breaking change and also less familiar for JS devs. Another option is to name the fold operation reduceWithInit, but that seems a bit backwards since it's the more common operation and is still a breaking change. I can't think of any better alternatives though.

The second problem is that reduce without an initial value will throw an error if the array is empty. The solution to that is pretty straightforward though, just add a wrapper with a check for an empty array or catch the error, and return an option. Since there's already a wrapper function to flip the arguments, that's not much of a problem.

Any ideas on how to proceed here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant