Math Plus
Why
There are dozens of math libraries out there. Why use this one?
No good reason, personal preference. It's a lightweight Math library that extends the standard Math object with some overridden functionality, added methods and classes.
Usage
The main reason I use this package is because I like the rest/spread syntax in es6.
Rather than this:
const random floor ceil = Math
I can do this:
Overridden Methods
The round()
, floor()
and ceil()
methods is overridden to take a second parameter
place.
// rounds to the nearest 0.1 = 10.6 // ceil to the nearest 10 = 110 // floor to the nearest 100 = 0
The random()
method is overridden to take up to three parameters:
min, max and seed.
// random value between 2 and 5 // Third argument acts as a seed, providing the same number
random
can also be used to return a random element from an array, string, or array-like.
Min and max are treated as index ranges.
const string = 'letters-are-cool' // Returns a letter between index 0 (min) and array.length(max) (non-inclusive)const randomChar = const array = 'one' 2 three: 3 // undefined as max will default to array.lengthconst randomItem = // array-likes must have have number indexes and a length propertyconst arrayLike = 0: 'one' 1: 'two' 2: 'three' length: 3 const randomArrayLikeItem = // iterables also work (Set, Map, any Object with Symbol.iterator)const iterable = 1 2 3 4const randomIterable =
See the Bindable Methods section for a cleaner syntax for the random
method.
Added Methods
The lerp()
method, which interpolates one value to another:
// lerp(from, to, interpolator) // 7.5 // 1.5 // 9
The clamp()
method, which is self explanatory
// clamp(value, min = 0, max = 1) // 1 // 1
The isPrime()
method, also self explanatory
// isPrime(value) // true // false
The primes()
method, which returns a generator that iterates prime numbers
const to10 = ... // [2,3,5,7,9] for const prime of console //logs every prime between 50 and 100
::
Bindable Methods I don't know if you have heard of the bind operator, but I LOVE the bind operator. Read more here: https://babeljs.io/docs/plugins/transform-function-bind/ Where-ever prudent, the overridden and custom methods allow numbers to be bound to them:
104:: //10 1000:: // binding a value to random gives it a seed // You can also bind arrays, iterables, array-likes or strings to the random method 'string':: // random char1234:: // random item // primes isn't bindable, but it does return an iterator:: // random prime number between 0 and 1000
List of all bindable methods:
lerp
, clamp
, isPrime
, round
, floor
, ceil
, pow
, abs
, acos
, acosh
, asin
, asinh
, atan
, atanh
, cbrt
, clz32
, cos
, cosh
, exp
, expm1
, fround
, log
, log10
, log1p
, log2
, sign
, sin
, sinh
, sqrt
, tan
, tanh
, trunc