Javascript provides a Math-object, that covers a broad range of useful constants and functions. However, sometimes it may happen, your are missing a function or the builtin function does not provide what you need. And - not everybody is happy that all Math-functions need to be prefixed by the word "Math". But luckily, Javascript is a flexible language and there is some help.
Extending the "Math"-object
Actually, it can be seen as a weak point, that Javascript objects do not have any access protection. In our current case, this is an advantage. You can easily add new functions to the "Math"-object or even change the inbuilt ones. Here is an example of the round()
-function, that does not allow to set decimals. But this can be easily fixed:
Math._round = Math.round
Math.round = (f, n = 0) => {
let m = Math.pow(10, n)
return (Math._round(f * m) / m)
}
Here, we store the initial round
function in a new property called _round
. Then we can overwrite the initial property with a new function.
We can also extend the Math-object with some useful stuff:
Math.PI2 = 2*Math.PI
// Range-Check: True if x in Range (L .. H)
Math.inRange = (x, L, H) => (x < L) ? false : x <= H
// Constrain value: Limit x to range (L .. H)
Math.constrain = (x, L, H) => x < L ? L : x > H ? H : x
The new functions work seamlessly as if they where inbuilt.
Math destructuring
So, and how to get rid of the Math
-prefix? You can use object
destructuring here:
let {sin, cos, round, inRange, constrain, PI, PI2} = Math
Now the functions are available in the global scope:
round(sin(0.1*PI2),3) // -> 0.588
inRange(3.158,2,4) // -> true
constrain(3.158,4,5) // -> 4
You can play around with the code in flems.io
Top comments (5)
Thank you Eckehard :-)
Please don't monkey patch built-ins!
Extending Math can be scoped, so I do not expect any trouble. Even destructuring should not cause more trouble than other naming conflicts. But you are perfectly true not to use it in libraries.
Thanks
Very helpful!