5 ms·
Well a bunch of standard libraries have sum defined, right? JavaScript has suffered from a lack of a standard library for a while. Having a small package like
by rtpg 11y ago
Well a bunch of standard libraries have sum defined, right?
JavaScript has suffered from a lack of a standard library for a while. Having a small package like this means that (in theory) everyone is using the same bug free version of summing instead of writing their own.
Honestly having JS start building a standard library at this point would be wonderful.
- guscost 11y agoThere's already `Array.prototype.reduce()` in most browsers, which will do summing, string concatenation, and any other kind of aggregation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... If you need something more convenient I highly recommend just adding lodash and getting a whole bag of rock-solid awesome tools.
- astrange 11y agoreduce isn't a safe way to add floating-point numbers unless your accumulator is much more precise than your array values. You'll end up with what they call "catastrophic cancellation". And they won't let you have fixed-point in JavaScript!
- guscost 11y agoDoesn't a for loop have the same problem?
- astrange 11y agoIf you write the loop yourself, you can add everything to a double instead of a float, or a long double instead of a double, if you have those. Oh, if all your numbers are positive you can also sort the array and it will minimize the error accumulated, but I'm not sure what to do with mixed signs.
- sotojuan 11y agoFor now I suggest using lodash functions exported as modules. For example: https://www.npmjs.com/package/lodash.mean https://www.npmjs.com/package/lodash.mean Or, in light of `left-pad`: https://www.npmjs.com/package/lodash.padstart https://www.npmjs.com/package/lodash.padstart You get the benefit of a "small, focused" module but still rely on a large and stable project with a great maintainer that cares about performance and testability.
- metaphorm 11y agohere is the source for that npm package https://github.com/bytespider/average/blob/master/src/average.js https://github.com/bytespider/average/blob/master/src/averag... and here is the code copied out in full module.exports = function average(values) { for (var i = 0, sum = 0; i < values.length; ++i) { sum += values[i]; } return sum / values.length; }; is this worth adding a dependency to your build for?