Additional Math functions
Sander Deryckere
sanderd17 at gmail.com
Wed Apr 29 14:00:05 UTC 2015
IMHO, there are still some rather basic Math functions missing in ES.
1. `Math.sum([value1[, value2[, value3[, ...]]]])`
A Math.sum() function would mostly be handy thanks to the spread operator.
So you can sum a complete array. Being able to do
```
var sum = Math.sum(...arr);
```
would be so much cleaner than
```
var sum = arr.reduce((a,b) => a + b);
```
Even though arrow functions make it a lot more concise than before, the
code with Math.sum is still a lot easier to read IMO.
Reference implementation:
```
Math.sum = function() {
var sum = 0;
var length = arguments.length;
for (var i = 0; i < length; i++) {
sum += +arguments[i]; // note the conversion to number, to avoid string
concatenation
}
return sum;
};
```
2. `Math.avg(value1[, value2[, value3[, ...]]])`
Calculating the average is just the sum divided by the number of values.
This might be less used, and when Math.sum is implemented, it might even be
clean enough to type something like
```
var avg = Math.sum(...arr) / arr.length;
```
Maybe it's also not used as often as summing an array. But I still expect
it would enhance the vanilla ES experience.
Reference implementation:
```
Math.avg = function() {
var sum = 0;
var length = arguments.length;
for (var i = 0; i < length; i++) {
sum += +arguments[i]; // note the conversion to number, to avoid string
concatenation
}
return sum / length;
}
```
3. `Math.clamp(value, min, max)`
This would basically be the same as
```
Math.max(Math.min(value, max), min);
```
Perhaps with extra consistency checks, throwing a rangeError when min>max
for example. The problem with combining Math.min and Math.max to achieve a
clamp function is that it's way too easy to mix them up, and get bugs in
your code.
There are of course other math functions that could be added (like the list
here: http://moutjs.com/docs/latest/math.html ), but I think that these
will be the more useful ones (also used more often than Math.hypot I
assume).
I do understand that a bloated language is in nobody's interest, but when
using reduce to sum an array, I always wondered if there's no other way to
do it. Without hacking on the language, and by typing what you mean. Thanks
to the spread operator, there now is a way to define such a function, but
sadly, there's no default function like that yet.
Thanks for your consideration,
Sander
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150429/f26aeafb/attachment-0001.html>
More information about the es-discuss
mailing list