NumUnit
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
0
Value data type
number

NumUnit vs number

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.
1
// initialization
2
let num = 42069; // a variable with prmitive number value
3
const unit = new NumUnit({initialValue: 42069});
4
// initialValue is optional, NumUnit has 0 as default value
5
​
6
num === unit // false
7
num === unit.value() // true
8
​
9
num.toString() // '42069'
10
numUnit.toString() // '42069'
11
​
12
num.toLocaleString() // '42,069' (in an 'en' locale)
13
numUnit.toLocaleString() // '42,069' (in an 'en' locale)
14
​
15
num + 1 // 42070
16
numUnit + 1 // 42070 // this doesn't change the Unit's value
17
​
18
num + 'XX' // '42069XX'
19
numUnit + 'XX' // '42069XX' // this doesn't change the Unit's value
20
​
21
typeof num === 'number' // true
22
typeof unit === 'object' // true
23
typeof unit.value() === 'number' // true
24
​
25
// value assignment
26
num = 7;
27
unit.dispatch(7);
28
​
29
// value access
30
console.log(num) // logs 7
31
console.log(unit.value()) // logs 7
32
// or
33
unit.subscribe(value => console.log(value)) // logs 7, will log future values
Copied!
Last modified 1yr ago
Copy link