UNPKG

2.8 kBTypeScriptView Raw
1import { IObservableArray, ObservableMap } from "mobx";
2/**
3 * Reactively sorts a base observable array into multiple observable arrays based on the value of a
4 * `groupBy: (item: T) => G` function.
5 *
6 * This observes the individual computed groupBy values and only updates the source and dest arrays
7 * when there is an actual change, so this is far more efficient than, for example
8 * `base.filter(i => groupBy(i) === 'we')`. Call #dispose() to stop tracking.
9 *
10 * No guarantees are made about the order of items in the grouped arrays.
11 *
12 * The resulting map of arrays is read-only. clear(), set(), delete() are not supported and
13 * modifying the group arrays will lead to undefined behavior.
14 *
15 * NB: ObservableGroupMap relies on `Symbol`s. If you are targeting a platform which doesn't
16 * support these natively, you will need to provide a polyfill.
17 *
18 * @param {array} base The array to sort into groups.
19 * @param {function} groupBy The function used for grouping.
20 * @param options Object with properties:
21 * `name`: Debug name of this ObservableGroupMap.
22 * `keyToName`: Function to create the debug names of the observable group arrays.
23 *
24 * @example
25 * const slices = observable([
26 * { day: "mo", hours: 12 },
27 * { day: "tu", hours: 2 },
28 * ])
29 * const slicesByDay = new ObservableGroupMap(slices, (slice) => slice.day)
30 * autorun(() => console.log(
31 * slicesByDay.get("mo")?.length ?? 0,
32 * slicesByDay.get("we"))) // outputs 1, undefined
33 * slices[0].day = "we" // outputs 0, [{ day: "we", hours: 12 }]
34 */
35export declare class ObservableGroupMap<G, T> extends ObservableMap<G, IObservableArray<T>> {
36 /**
37 * Base observable array which is being sorted into groups.
38 */
39 private readonly _base;
40 /**
41 * The ObservableGroupMap needs to track some state per-item. This is the name/symbol of the
42 * property used to attach the state.
43 */
44 private readonly _ogmInfoKey;
45 /**
46 * The function used to group the items.
47 */
48 private readonly _groupBy;
49 /**
50 * This function is used to generate the mobx debug names of the observable group arrays.
51 */
52 private readonly _keyToName;
53 private readonly _disposeBaseObserver;
54 constructor(base: IObservableArray<T>, groupBy: (x: T) => G, { name, keyToName, }?: {
55 name?: string;
56 keyToName?: (group: G) => string;
57 });
58 clear(): void;
59 delete(_key: G): boolean;
60 set(_key: G, _value: IObservableArray<T>): this;
61 /**
62 * Disposes all observers created during construction and removes state added to base array
63 * items.
64 */
65 dispose(): void;
66 private _getGroupArr;
67 private _removeFromGroupArr;
68 private _addItem;
69 private _removeItem;
70}