1 import type { Listeners } from './listeners';
2 import createListeners from './listeners';
4 export interface Cache<K, V> extends Pick<Listeners<[K, V | undefined], void>, 'subscribe'>, Map<K, V> {
5 clearListeners: () => void;
9 * Wraps a map with support for subscribe/unsubscribe on changes.
11 const createCache = <K, V>(map = new Map<K, V>()): Cache<K, V> => {
12 const listeners = createListeners<[K, V | undefined], void>();
17 forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any) {
18 return map.forEach(callbackfn, thisArg);
20 has: (key: K) => map.has(key),
21 get: (key: K) => map.get(key),
22 entries: () => map.entries(),
23 keys: () => map.keys(),
24 values: () => map.values(),
25 [Symbol.iterator]: () => map[Symbol.iterator](),
26 get [Symbol.toStringTag]() {
27 return map[Symbol.toStringTag];
29 clear: () => map.clear(),
31 const r = map.delete(key);
32 listeners.notify(key, undefined);
35 set(key: K, value: V) {
37 listeners.notify(key, value);
40 subscribe: listeners.subscribe,
41 clearListeners: listeners.clear,
45 export default createCache;