mobx-utils
Version:
Utility functions and common patterns for MobX
71 lines (70 loc) • 2.8 kB
TypeScript
import { IObservableArray, ObservableMap } from "mobx";
/**
* Reactively sorts a base observable array into multiple observable arrays based on the value of a
* `groupBy: (item: T) => G` function.
*
* This observes the individual computed groupBy values and only updates the source and dest arrays
* when there is an actual change, so this is far more efficient than, for example
* `base.filter(i => groupBy(i) === 'we')`. Call #dispose() to stop tracking.
*
* No guarantees are made about the order of items in the grouped arrays.
*
* The resulting map of arrays is read-only. clear(), set(), delete() are not supported and
* modifying the group arrays will lead to undefined behavior.
*
* NB: ObservableGroupMap relies on `Symbol`s. If you are targeting a platform which doesn't
* support these natively, you will need to provide a polyfill.
*
* @param {array} base The array to sort into groups.
* @param {function} groupBy The function used for grouping.
* @param options Object with properties:
* `name`: Debug name of this ObservableGroupMap.
* `keyToName`: Function to create the debug names of the observable group arrays.
*
* @example
* const slices = observable([
* { day: "mo", hours: 12 },
* { day: "tu", hours: 2 },
* ])
* const slicesByDay = new ObservableGroupMap(slices, (slice) => slice.day)
* autorun(() => console.log(
* slicesByDay.get("mo")?.length ?? 0,
* slicesByDay.get("we"))) // outputs 1, undefined
* slices[0].day = "we" // outputs 0, [{ day: "we", hours: 12 }]
*/
export declare class ObservableGroupMap<G, T> extends ObservableMap<G, IObservableArray<T>> {
/**
* Base observable array which is being sorted into groups.
*/
private readonly _base;
/**
* The ObservableGroupMap needs to track some state per-item. This is the name/symbol of the
* property used to attach the state.
*/
private readonly _ogmInfoKey;
/**
* The function used to group the items.
*/
private readonly _groupBy;
/**
* This function is used to generate the mobx debug names of the observable group arrays.
*/
private readonly _keyToName;
private readonly _disposeBaseObserver;
constructor(base: IObservableArray<T>, groupBy: (x: T) => G, { name, keyToName, }?: {
name?: string;
keyToName?: (group: G) => string;
});
clear(): void;
delete(_key: G): boolean;
set(_key: G, _value: IObservableArray<T>): this;
/**
* Disposes all observers created during construction and removes state added to base array
* items.
*/
dispose(): void;
private _getGroupArr;
private _removeFromGroupArr;
private _addItem;
private _removeItem;
}