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.
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.
// initializationlet str ='Hello';constunit=newStringUnit({initialValue:'Hello'});str === unit // falsestr ===unit.value() // trueunit +' World'// 'Hello World'unit +1// 'Hello1'unit.dispatch('6');parseInt(unit) // 6typeof str ==='string'// truetypeof unit ==='object'// truetypeofunit.value() ==='string'// true// value assignmentstr ='bye';unit.dispatch('bye');// value accessconsole.log(str) // logs 'bye'console.log(unit.value()) // logs 'bye'// ORunit.subscribe(value=>console.log(value)) // logs 'bye', will log future values