mathmethods
npm install mathmethods
mathmethods is a tiny script which makes methods of the Math
object
available to numbers by adding properties to Number.prototype
. This makes it
possible to write certain expressions in a more expressive (Ruby-like) manner.
For each Math
method, a property is added to Number.prototype
. Accessing
one of these properties invokes the appropriate method with the number as the
first argument. The majority of the Math
methods take exactly one argument,
so parentheses are not required.
dollars = balancefloor // dollars = Math.floor(balance) width = $navleftabs // width = Math.abs($nav.offset().left) Infinityatanlogsqrt // Math.sqrt(Math.log(Math.atan(Infinity)))
A few Math
methods – atan2
, max
, min
, and pow
– take more than one
argument. When a property corresponding to one of these methods is accessed,
a callable is returned which accepts the remaining arguments.
x // Math.pow(x, y) fee = 0 // fee = Math.max(0, rate * hours - advance) kimwage = 10 // kim.wage = Math.min(10, ian.wage, jan.wage)
random
Math.random
takes zero arguments. For consistency with the other
methods, Number.prototype.random
produces a number between 0 and this
.
100..random
, for example, produces a number between 0 and 100.
1random // Math.random() // simluate a die roll6randomfloor + 1 // Math.floor(6 * Math.random()) + 1
squared
and cubed
Shorthands for the equivalent .pow
s.
area = widthsquared // area = Math.pow(width, 2) volume = xcubed // volume = Math.pow(x, 3)
fact
Gives the number's factorial. Throws a RangeError if the number is negative; a TypeError if the number is not an integer.
5fact // 5 * 4 * 3 * 2 * 1
Running the test suite
make setup
make test
Internet Explorer
There's a bug in IE9 which breaks getters for number primitives which are
integers. To accommodate IE9 one must work with Number
objects exclusively.
dollars = balancefloor // dollars = Math.floor(balance)
This introduces unacceptable noise. One can quieten it to a certain extent by
defining a function which returns a Number
object whose value is equivalent
to that of the provided argument.
{ return n } dollars = floor // dollars = Math.floor(balance) width = abs // width = Math.abs($nav.offset().left) Infinityatanlogsqrt // Math.sqrt(Math.log(Math.atan(Infinity))) // Math.pow(x, y) fee = // fee = Math.max(0, rate * hours - advance) kimwage = // kim.wage = Math.min(10, ian.wage, jan.wage) random // Math.random() randomfloor + 1 // Math.floor(6 * Math.random()) + 1 area = squared // area = Math.pow(width, 2) volume = cubed // volume = Math.pow(x, 3)
A better workaround would be extremely gratefully received!