NumUnit is a type of Unit that only accepts number
data type as its value. It ensures that at any point of time the value would always be number
.
It doesn't even accept NaN
as it's value.
It implements all the Number.prototype methods available in the environment/browser, including polyfills.
e.g.:toFixed
and toString
, and redirects them to the stored number
value inside the Unit, so when you call Unit.toString()
, it'll be executed on the Unit's value instead of the NumUnit instance itself.
See API reference for more details.
| |
Default value |
|
Value data type |
|
NumUnit can not be used as a drop-in replacement for primitive number
value, since NumUnit is a non-primitive data structure, and the actual number
value is stored inside the Unit. See the below comparisons for more clarity.
// initializationlet num = 42069; // a variable with prmitive number valueconst unit = new NumUnit({initialValue: 42069});// initialValue is optional, NumUnit has 0 as default valuenum === unit // falsenum === unit.value() // truenum.toString() // '42069'numUnit.toString() // '42069'num.toLocaleString() // '42,069' (in an 'en' locale)numUnit.toLocaleString() // '42,069' (in an 'en' locale)num + 1 // 42070numUnit + 1 // 42070 // this doesn't change the Unit's valuenum + 'XX' // '42069XX'numUnit + 'XX' // '42069XX' // this doesn't change the Unit's valuetypeof num === 'number' // truetypeof unit === 'object' // truetypeof unit.value() === 'number' // true// value assignmentnum = 7;unit.dispatch(7);// value accessconsole.log(num) // logs 7console.log(unit.value()) // logs 7// orunit.subscribe(value => console.log(value)) // logs 7, will log future values