diff --git a/package.json b/package.json index b0a111a..9e93908 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@yermak/derived", - "version": "1.0.0", + "version": "1.0.1", "description": "State manager library", "main": "./dist/index.js", "module": "./dist/index.js", diff --git a/src/index.ts b/src/index.ts index c7ec9df..4e40857 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,3 +3,4 @@ export { derived, type DerivedType } from './derived'; export { async, type AsyncType } from './async'; export { map, type MapType } from './map'; export { useObservable, type ObservableType } from './observable'; +export { observer, type Observer } from './observer'; diff --git a/src/map.ts b/src/map.ts index 5e2f883..1892718 100644 --- a/src/map.ts +++ b/src/map.ts @@ -1,4 +1,3 @@ -import { ObservableType } from './observable'; import { observer } from './observer'; import { store, StoreType } from './store'; @@ -6,11 +5,8 @@ type MapValue = Record; type MapItemStore = StoreType; -export interface MapType extends ObservableType>> { +export interface MapType { item: (key?: K | null | undefined) => MapItemStore; - has: (key: K) => boolean; - set: (key: K, value: V) => void; - delete: (key: K) => void; } export function map(initialValue?: MapValue): MapType { @@ -18,44 +14,46 @@ export function map(initialValue?: MapValue): MapT type ItemValue = V | undefined; const _observer = observer>(); + const undefinedStore = store(undefined); const map = new Map(); - if (initialValue) { - for (let key in initialValue) { - const value = store(initialValue[key]); - map.set(key, value); + + const addStore = (key: K, value: ItemValue): ItemStore => { + const valueStore = store(value); + map.set(key, valueStore); + return valueStore; + }; + + const getStore = (key: K): ItemStore => { + const valueStore = map.get(key); + if (valueStore === undefined) { + return addStore(key, undefined); } + return valueStore; + }; + + for (let key in initialValue) { + addStore(key, initialValue[key]); } return { - get: () => map, item: (key?: K | null | undefined) => { if (key === null || key === undefined) { return undefinedStore; } - let valueStore = map.get(key); - if (valueStore === undefined) { - valueStore = store(undefined); - map.set(key, valueStore); - } - return valueStore; - }, - has: (key: K) => map.has(key), - set: (key: K, value: V) => { - const valueStore = map.get(key); - if (valueStore === undefined) { - map.set(key, store(value)); - _observer.notify(map); - return; - } - if (valueStore.get() !== value) { - valueStore.set(value); - _observer.notify(map); - return; - } + const valueStore = getStore(key); + return { + set: (newValue) => { + if (valueStore.get() === newValue) { + return; + } + valueStore.set(newValue); + _observer.notify(new Map(map)); + }, + get: valueStore.get, + subscribe: valueStore.subscribe, + }; }, - delete: (key: K) => map.delete(key), - subscribe: _observer.subscribe, }; }