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

fix: Sum of zero elements equals zero #294

Closed
wants to merge 1 commit into from

Conversation

artyomxyz
Copy link

I believe sum of zero elements equals zero. Current implementation produces NaN for this case.

@shuckster
Copy link

In plain JavaScript, how does the length of a set correlate with its type?

@MikeMcl
Copy link
Owner

MikeMcl commented Jun 7, 2021

I don't think that convention would be useful here. I think it is better to indicate a probable mistake with NaN.

The current behaviour is consistent with other operations, e.g. BigNumber(1).plus() // NaN.

@artyomxyz
Copy link
Author

artyomxyz commented Jun 8, 2021

I don't think that convention would be useful here. I think it is better to indicate a probable mistake with NaN.

The current behaviour is consistent with other operations, e.g. BigNumber(1).plus() // NaN.

Big difference here is that .plus expects exactly one number, while sum expects set of numbers. And it is consistent with mathematical definition of sum.

Imagine we have a cart and products in it. We want to display total price of products.
BigNumber.sum(...cart.products.map(p => p.price)). For empty cart it's NaN. What kind of error we want to indicate here? Still if we pass undefined as first argument we would receive NaN because it's an error

https://en.wikipedia.org/wiki/Empty_sum

@MikeMcl
Copy link
Owner

MikeMcl commented Jun 9, 2021

Big difference here is that .plus expects exactly one number, while sum expects set of numbers.

Here, sum expects one or more numbers.

Imagine we have a cart and products in it.

Right, it's shopping, not formal mathematics.

For empty cart it's NaN. What kind of error we want to indicate here?

That there is nothing to sum?

Still if we pass undefined as first argument we would receive NaN because it's an error.

NaN is returned because undefined is not a number.

I agree that in some situations it would be useful for zero to be returned, but it would need to be applied consistently so:

BigNumber();           // 0
BigNumber(1).plus();   // 1
BigNumber.sum();       // 0
// etc.

I will consider it further but I am not convinced atm.

@artyomxyz artyomxyz closed this Oct 16, 2023
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

Successfully merging this pull request may close these issues.

None yet

3 participants