-
Notifications
You must be signed in to change notification settings - Fork 478
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
Decimal.sum to support no arguments #207
Comments
I think this has been requested before. Should And the prototype methods? new Decimal(1).add() // => new Decimal(1) Personally, I think it is better (safer) to throw when undefined is passed. |
Math.max() // => -Infinity
Math.min() // => Infinity So, I propose that Decimal.max() // => new Decimal(-Infinity)
Decimal.min() // => new Decimal(Infinity) |
Just my user voice but I highly appreciate the simplicity of the lib as it is. Not having to remember these kind of subtleties is a plus. |
For my use case, I need to retrieve the sum of a highly nested and filtered array of objects, and it would be very convenient if I'd love to be able to do this: const value = Decimal.sum(...myArray.filter(filterFunc).map(mapFunc)) But because const value =
myArray.filter(filterFunc).length > 0
? Decimal.sum(...myArray.filter(filterFunc).map(mapFunc))
: new Decimal(0) (In reality, I have many more filters and maps than this example, but it paints the picture) Though honestly, I think it would be ideal if |
The concern is legit since some popular libs do this, it could make a useful option. Note that you can still one line your sum with myArr.reduce((a: Decimal, b: Decimal) => a.plus(b), new Decimal(0))
// or even without acc
myArr.reduce((a: Decimal, b: Decimal) => a.plus(b)) |
I just ran into this issue, it is not obvious that |
Yeah, still don't really love the API here. I ended up just making a utility function which accepts an array (instead of multiple arguments), and returns 0 for an empty array or undefined argument: import Decimal from 'decimal.js'
/**
* Sum an array of Decimal values, returning 0 for undefined or empty arrays.
*/
export default function sumDecimal(decimals?: Decimal[]): Decimal {
return !decimals || decimals.length === 0
? new Decimal(0)
: Decimal.sum(...decimals)
} |
If an empty array as argument crashes, the function should not accept 0 arguments? |
My colleague suggested a nice workaround: const decimals = []
Decimal.sum(0, ...decimals) // No error! :D |
Currently, an error occurs when zero arguments is passed to
Decimal.sum
.Lodash's
_.sum
and Ramda'sR.sum
returns0
when passed an array with zero elements.Similarly, it would be nice if
Decimal.sum
returnednew Decimal(0)
when called with zero arguments.The text was updated successfully, but these errors were encountered: