StringUnit
StringUnit is a type of Unit that only accepts string data type as its value. It ensures that at any point of time the value would always be string.
It implements all the String.prototype methods available in the environment/browser, including polyfills. e.g.: trim, includes and toLowerCase , etc., and redirects them to the stored string value inside the Unit, so when you call Unit.includes() , it'll be executed on the Unit's value instead of the Unit instance itself.
When we use String.prototype methods like replace, it doesn't mutate the value of the Unit, similar to how simple String.prototype.replace works.
See API reference for more details.
​
​
Default value
'' (empty string)
Value data type
string

StringUnit vs string

StringUnit can not be used as a drop-in replacement for primitive string value, since StringUnit is a non-primitive data structure, and the actual string value is stored inside the Unit, which can be accessed viaUnit.value() method. See the below comparisons for more clarity.
1
// initialization
2
let str = 'Hello';
3
const unit = new StringUnit({initialValue: 'Hello'});
4
​
5
str === unit // false
6
str === unit.value() // true
7
​
8
unit + ' World' // 'Hello World'
9
unit + 1 // 'Hello1'
10
unit.dispatch('6');
11
parseInt(unit) // 6
12
​
13
typeof str === 'string' // true
14
typeof unit === 'object' // true
15
typeof unit.value() === 'string' // true
16
​
17
// value assignment
18
str = 'bye';
19
unit.dispatch('bye');
20
​
21
// value access
22
console.log(str) // logs 'bye'
23
console.log(unit.value()) // logs 'bye'
24
// OR
25
unit.subscribe(value => console.log(value)) // logs 'bye', will log future values
Copied!
Last modified 10mo ago
Copy link