@lexriver/observable
TypeScript icon, indicating that this package has built-in type declarations

2.2.0 • Public • Published

Observable

This package provides observable data structures:

Install

npm install @lexriver/observable

Import

import {ObservableVariable, ObservableArray, ObservableMap, ObservableLocalStorageVariable, ObservableLocalStorageArray, createObservable, checkIfObservable } from '@lexriver/observable'

Example of usage

const myNumberO = new ObservableVariable<number>(100) // 100 is initial value

// subscribe to event on change
myNumberO.eventOnChange.subscribe((newValue, prevValue) => {
    console.log('newValue=', newValue, 'prevValue=', prevValue)
})

console.log('myNumberO=', myNumberO.get()) // 100

myNumberO.set(200)

console.log('myNumberO=', myNumberO.get()) // 200

Yes, it's recommended to add suffix capital "O" for convenience and not to compare values directly by mistake

myNumberO === 100 // WRONG!
myNumberO.get() === 100 // correct






ObservableVariable<T>

Use this class to create observable variable. Variable can be of any type, but the eventOnChange will be triggered only on .set(..) method. So for array and map use ObservableArray<T> and ObservableMap<K,V>.

const myStringO = new ObservableVariable<string>('default text')

eventOnChange:TypeEvent<(newValue:T, prevValue?:T)=>void>

This event will be triggered every time the value changes.

myStringO.eventOnChange.subscribe((newValue, prevValue) => {
    console.log('the value was changed from ', prveValue, 'to', newValue)
})

For more details on TypeEvent please visit https://github.com/LexRiver/type-event


set(value:T)

Set new value.

myStringO.set('new value')

This method triggers .eventOnChange event


setByPrevious(setter:(oldValue:T)=>T)

Set new value by previous value.

myStringO.set((previous) => previous+'!')

This method will also trigger .eventOnChange.


get()

Get current value.

let result = myStringO.get()






ObservableArray<T>

Example of usage

const myArrayO = new ObservableArray<number>() 

myArrayO.eventOnChange.subscribe(() => console.log('array was changed'))

myArrayO.push(100)
console.log(myArrayO[0]) // 100
myArrayO[0] = 200
console.log(myArrayO[0]) // 200

Create observable array

// init with empty array
const myArrayO = new ObservableArray<number>() 

// init with exact array
const myAnotherArrayO = new ObservableArray<number>([1,2,3])

eventOnChange:TypeEvent<(changedItem?:T)=>void>

This event will be triggered every time the array changes.

myArrayO.eventOnChange.subscribe((changedItem) => {
    console.log('array was changed')
    if(changedItem){
        console.log('changed item=', changedItem)
    }
})

For more details on TypeEvent please visit https://github.com/LexRiver/type-event


length

Property to get length of the array.

myArrayO.length 

getInternalArray():T[]

Get current internal array.

Warning: modifying the result value will cause original elements to change without triggering the event!

myArrayO.set([100,200])
let result = myArrayO.getInternalArray() // [100,200]
result.push(300) // .eventOnChange is not triggered here!
myArrayO.getInternalArray() // [100, 200, 300] !

toArray():T[] or getAsArray():T[]

Get current array as a copy.

myArrayO.set([100,200])
let copy = myArrayO.toArray()
copy.push(300)
copy // [100,200,300]
myArrayO.toArray() // [100,200]


set(items:T[])

Replace array with new items

myArrayO.set([2,3,4])

This method triggers .eventOnChange


setByPrevious(setter:(oldValue:T[])=>T[])

Replace array with new items using current values

myArrayO.setByPrevious((oldArray:number[]) => oldArray.filter(x => x>0))

This method triggers .eventOnChange


appendArray(arrayToAppend:T[])

Append array to current array.

myArrayO.set([1,2,3])
myArrayO.appendArray([4,5,6])
myArrayO.get() // [1,2,3,4,5,6]

This method triggers .eventOnChange


every(conditionToCheck:(value:T, index?:number, array?:T[])=>boolean)

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

myArrayO.every(x => x>0)

fill(value:T, start?:number, end?:number)

The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array.

myArrayO.fill(100, 0, 10) // fill 10 first items with 100 value

This method triggers .eventOnChange


filter(action:(value:T, index?:number, array?:T[])=>boolean)

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

myArrayO.filtex(x => x === 0)

find(predicate:(value:T, index?:number, array?:T[])=>boolean)

The find() method returns the value of the first element in the provided array that satisfies the provided testing function.

myArrayO.find(x => x>0)

findIndex(predicate:(value:T, index?:number, array?:T[])=>boolean)

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.

myArrayO.findIndex(x => x>0)

forEach(action:(value:T, index?:number, array?:T[])=>void, thisArg?:any)

The forEach() method executes a provided function once for each array element.

myArrayO.forEach(x => {
    console.log(x)
})

includes(searchElement:T, fromIndex?:number):boolean

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

myArrayO.includes(100) 

indexOf(searchElement:T, fromIndex?:number):number

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

myArrayO.indexOf(100)

join(separator?:string):string

The join() method creates and returns a new string by concatenating all of the elements in an array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

myArrayO.join(', ')

keys()

The keys() method returns a new Array Iterator object that contains the keys for each index in the array

for(let k of myArrayO.keys()){
    console.log(k)
}

lastIndexOf(searchElement:T, fromIndex?:number):number

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.

myArrayO.lastIndexOf(100)

map(action:(value:T, index?:number, array?:T[])=>void, thisArg?:any)

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

myArrayO.map(x => x+1)

pop():T

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

myArrayO.pop()

This method triggers .eventOnChange


push(item:T):number

The push() method adds zero or more elements to the end of an array and returns the new length of the array.

myArrayO.push(200)

This method triggers .eventOnChange


reduce<R>(action:(accumulator:R, value:T, index?:Number) => R, initValue:R)

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

myArrayO.reduce((result, value) => result += value, 0)

reduceRight<R>(action:(accumulator:R, value:T, index?:Number) => R, initValue:R)

The reduceRight() method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.

myArrayO.reduceRight((result, value) => result += value+'--', '--')

reverse()

The reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.

myArrayO.reverse()

This method triggers .eventOnChange


shift(): T | undefined

Removes the first element from an array and returns it.

let first = myArrayO.shift()

This method triggers .eventOnChange


slice(start?:number, end?:number):T[]

Returns a section of an array.

myArrayO.slice(2,4)

some(predicate:(value:T, index?:number, array?:T[])=>boolean, thisArg?:any):boolean

Determines whether the specified callback function returns true for any element of an array.

myArrayO.some(x = x>0)

sort(compareFn?:(a:T, b:T)=>number)

Sorts an array in place.

myArrayO.sort()

This method triggers .eventOnChange


splice(start: number, deleteCount: number, ...items: T[]): T[]

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

myArrayO.splice(0, 1, 1000) // replace first element

This method triggers .eventOnChange


toString()

A string representing the elements of the array.

myArrayO.toString()

unshift(...items: T[]): number

Inserts new elements at the start of an array.

myArrayO.unshift(10, 20)

This method triggers .eventOnChange

values()

Returns an iterable of values in the array

getByIndex(index:number)

Get element by index.

myArrayO.getByIndex(0)
myArrayO[0] // the same

setByIndex(index:number, value:T)

Set new value by index.

myArrayO.setByIndex(2, 200)
myArrayO[2] = 200 //the same

This method triggers .eventOnChange

removeItemByIndex(index:number)

Delete element by index.

myArrayO.removeItemByIndex(2)

This method triggers .eventOnChange







ObservableMap<K,V>

Example of usage

let myMapO = new ObservableMap<string, number>()
myMapO.eventOnChange.subscribe((k,v) => {
    console.log('k=', k, 'v=', v)
})
myMapO.set('one', 1)
expect(myMapO.get('one')).toEqual(1)
expect(counter).toEqual(1)

Create ObservableMap

const myMapO = new ObservableMap<string, number>()
const myAnotherMapO = new ObservableMap<string, number>([['one', 1], ['two', 2]])

eventOnChange:TypeEvent<(key?:K, value?:V)=>void>

This event will be triggered every time the map changes

myMapO.eventOnChange.subscribe((key, value) => {
    console.log('map was changed', 'key=', key, 'value=', value)
})

eventOnChangeKey:TypeEvent<(key:K, value:V)=>void>

This event will be triggered every time some key was changed or added or deleted.

myMapO.eventOnChangeKey.subscribe((key, value) => {
    console.log('key was changed', key, 'value=', value)
})

eventOnDeleteKey:TypeEvent<(key:K)=>void>

This event will be triggered every time key was deleted.

myMapO.eventOnDeleteKey.subscribe((key) => {
    console.log('key was deleted', key)
})

eventOnClear:TypeEvent<() => void>

This event will be triggered every time map was cleared.

myMapO.eventOnClear.subscribe(() => {
    console.log('map is empty')
})

entries()

The entries() method returns a new Iterator object that contains the [key, value] pairs for each element in the Map object in insertion order.

for(let [k,v] of myMapO.entries()){
    console.log('key=', k, 'value=', v)
}

has(key:K):boolean

The has() method returns a boolean indicating whether an element with the specified key exists or not.

myMapO.has('some key') // true or false

forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void

The forEach() method executes a provided function once per each key/value pair in the Map object, in insertion order.

myMapO.forEach((value, key) => {
    console.log('key=', key, 'value=', value)
})

set(key:K, value:V)

Add or set new value for key.

myMapO.set('my key', 200)

This method triggers .eventOnChangeKey and .eventOnChange


get(key:K):V|undefined

Get value by key or undefined.

myMapO.get('my key')

toArray()

Create new array from map.

myMapO.toArray()

initFromArray(mapEntries:Iterable<readonly [K, V]>)

Replace all values in map by values from array.

myMapO.initFromArray([['k1', 1], ['k2', 2]])

This method triggers .eventOnChange


delete(key:K)

Delete key from map.

myMapO.delete('my key')

This method triggers .eventOnDeleteKey and .eventOnChange if key exists.


clear()

Clear all keys from map.

myMapO.clear()

This method triggers .eventOnClear and .eventOnChange.


keys()

The keys() method returns a new Iterator object that contains the keys for each element in the Map object in insertion order.

for(let key of myMapO.keys()){
    console.log('key=', key)
}

values()

The values() method returns a new Iterator object that contains the values for each element in the Map object in insertion order.

for(let value of myMapO.values()){
    console.log('value=', value)
}

isEmpty():boolean

Check is map is empty.

myMapO.isEmpty() // true or false

size:number

Get size of map.

console.log('size of map is ', myMapO.size)






ObservableLocalStorageVariable

ObservableLocalStorageVariable allows to track changes for value in localStorage in browser.

const myStringO = new ObservableLocalStorageVariable<string>({
    localStorageKey: 'my-key-in-local-storage',
    defaultValueIfNotInLocalStorage: 'default text' // optional
})

eventOnChange:TypeEvent<(newValue:T, prevValue?:T)=>void>

This event will be triggered every time the value changes.

myStringO.eventOnChange.subscribe((newValue, prevValue) => {
    console.log('the value was changed from ', prveValue, 'to', newValue)
})

For more details on TypeEvent please visit https://github.com/LexRiver/type-event


set(value:T)

Set new value.

myStringO.set('new value')

This method triggers .eventOnChange event


setByPrevious(setter:(oldValue:T)=>T)

Set new value by previous value.

myStringO.set((previous) => previous+'!')

This method will also trigger .eventOnChange.


get()

Get current value.

let result = myStringO.get()

ObservableLocalStorageArray

ObservableLocalStorageArray allows to track changes for array in localStorage in browser. Most methods are the same as in ObservableArray but it stores value in localStorage and triggers event when the value is changed.





createObservable

A special function createObservable(myValue) can be used to create observable from existed value. Function accept only one parameter of any of these types:

  • string
  • number
  • boolean
  • Array
  • Map
export function createObservable(x:string):ObservableVariable<string>;
export function createObservable(x:number):ObservableVariable<number>;
export function createObservable(x:boolean):ObservableVariable<boolean>;
export function createObservable<T extends Array<V>, V>(x:Array<V>):ObservableArray<V>;
export function createObservable<T extends Map<K,V>, K, V>(x:Map<K,V>):ObservableMap<K,V>;

example to create ObservableVariable<string>

    let obsStringO = createObservable('default string')
    obsStringO.eventOnChange.subscribe((x) => console.log('obsString change', x))
    obsStringO.set('another string')

example to create ObservableMap<string, number>

    let map = new Map<string, number>()
    let obsMapO = createObservable(map)
    obsMapO.eventOnChange.subscribe((k,v) => console.log('obsMap change', k, v))
    obsMapO.set('one', 100)
    obsMapO.set('two', 200)



checkIfObservable

Use function checkIfObservable(o:any) to check if variable is any of type:

  • ObservableVariable
  • ObservableArray
  • ObservableMap

example

    let obsStringO = createObservable('default string')
    let myNumberO = new ObservableVariable<number>(100)
    let myMapO = new ObservableMap<string, number>()
    let myBoolean = false
    checkifObservable(obsStringO) // true
    checkifObservable(myNumberO) // true
    checkifObservable(myMapO) // true
    checkifObservable(myBoolean) // false

Package Sidebar

Install

npm i @lexriver/observable

Weekly Downloads

2

Version

2.2.0

License

MIT

Unpacked Size

139 kB

Total Files

44

Last publish

Collaborators

  • lexriver