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.

// initialization
let num = 42069; // a variable with prmitive number value
const unit = new NumUnit({initialValue: 42069});
// initialValue is optional, NumUnit has 0 as default value

num === unit // false
num === unit.value() // true

num.toString() // '42069'
numUnit.toString() // '42069'

num.toLocaleString() // '42,069' (in an 'en' locale)
numUnit.toLocaleString() // '42,069' (in an 'en' locale)

num + 1 // 42070
numUnit + 1 // 42070 // this doesn't change the Unit's value

num + 'XX' // '42069XX'
numUnit + 'XX' // '42069XX' // this doesn't change the Unit's value

typeof num === 'number' // true
typeof unit === 'object' // true
typeof unit.value() === 'number' // true

// value assignment
num = 7;
unit.dispatch(7);

// value access
console.log(num) // logs 7
console.log(unit.value()) // logs 7
// or
unit.subscribe(value => console.log(value)) // logs 7, will log future values

Last updated