UNPKG

indexed-collection

Version:

A zero-dependency library of classes that make filtering, sorting and observing changes to arrays easier and more efficient.

645 lines (627 loc) 18.8 kB
//#region src/builders/keyExtractBuilder.ts function buildMultipleKeyExtract(getKeys) { const result = (item) => getKeys(item); result.isMultiple = true; return result; } //#endregion //#region src/core/defaultCollectionViewOption.ts const defaultFilter = () => true; const defaultSort = () => 0; const defaultCollectionViewOption = Object.freeze({ filter: defaultFilter, sort: defaultSort }); //#endregion //#region src/signals/Signal.ts /** * Signal is a base class for all signals. * */ var Signal = class { constructor(type, target) { this.type = type; this.target = target; } }; //#endregion //#region src/signals/CollectionAddSignal.ts var CollectionAddSignal = class CollectionAddSignal extends Signal { static type = Symbol("COLLECTION_ADD"); constructor(target, added) { super(CollectionAddSignal.type, target); this.added = added; } }; //#endregion //#region src/signals/CollectionChangeSignal.ts var CollectionChangeSignal = class CollectionChangeSignal extends Signal { static type = Symbol("COLLECTION_CHANGE"); constructor(target, detail) { super(CollectionChangeSignal.type, target); this.detail = detail; } }; //#endregion //#region src/signals/CollectionRemoveSignal.ts var CollectionRemoveSignal = class CollectionRemoveSignal extends Signal { static type = Symbol("COLLECTION_REMOVE"); constructor(target, removed) { super(CollectionRemoveSignal.type, target); this.removed = removed; } }; //#endregion //#region src/signals/CollectionUpdateSignal.ts var CollectionUpdateSignal = class CollectionUpdateSignal extends Signal { static type = Symbol("COLLECTION_UPDATE"); constructor(target, updated) { super(CollectionUpdateSignal.type, target); this.updated = updated; } }; //#endregion //#region src/signals/SignalObserver.ts /** * Signal observer is a class that can be used to observe signals * It supports multiple observers for a single signal type and vice versa */ var SignalObserver = class { typeToHandleMap; handlerToTypeMap = /* @__PURE__ */ new Map(); constructor() { this.typeToHandleMap = /* @__PURE__ */ new Map(); } /** * Notify all observers of a signal by the signal's type * @param signal */ notifyObservers(signal) { const handlers = this.typeToHandleMap.get(signal.type); if (handlers) for (const handler of handlers) handler(signal); } /** * Register an observer for a signal type * @param type The type of a signal * @param handler The handler to be called when the signal is emitted */ registerObserver(type, handler) { const handlers = this.typeToHandleMap.get(type) ?? /* @__PURE__ */ new Set(); handlers.add(handler); this.typeToHandleMap.set(type, handlers); const types = this.handlerToTypeMap.get(handler) ?? /* @__PURE__ */ new Set(); types.add(type); this.handlerToTypeMap.set(handler, types); } /** * Unregister an observer for a signal type * @param handler The handle to be unregistered * @param type (Optional) The type of a signal (if not provided, all types associated with the handle will be unregistered) */ unregisterObserver(handler, type) { let relevantSignalTypes; if (type == null) relevantSignalTypes = this.handlerToTypeMap.get(handler); else relevantSignalTypes = new Set([type]); for (const type$1 of relevantSignalTypes) { const handlers = this.typeToHandleMap.get(type$1); if (handlers) handlers.delete(handler); } this.handlerToTypeMap.delete(handler); } }; //#endregion //#region src/collections/util.ts function mergeCollectionChangeDetail(a, b) { const added = a.added ? b.added ? a.added.concat(b.added) : a.added : b.added; const removed = a.removed ? b.removed ? a.removed.concat(b.removed) : a.removed : b.removed; const updated = a.updated ? b.updated ? a.updated.concat(b.updated) : a.updated : b.updated; return { added: added ?? [], removed: removed ?? [], updated: updated ?? [] }; } function filterCollectionChangeDetail(change, filter) { const added = change.added.filter(filter); const removed = change.removed.filter(filter); const updated = change.updated.filter((item) => filter(item.newValue)); return { added, removed, updated }; } //#endregion //#region src/collections/CollectionViewBase.ts /** * CollectionView is a view onto a collection of data. Most common use case would be * having the collection reduced by filter and/or sorted according to various criteria * without modifying the underlying data. */ var CollectionViewBase = class extends SignalObserver { _source; _option; _cachedItems = []; constructor(source, option = defaultCollectionViewOption) { super(); this._source = source; this._option = Object.assign({}, defaultCollectionViewOption, option); this.rebuildCache(); this._source.registerObserver(CollectionChangeSignal.type, this.source_onChange.bind(this)); } /** * Reindex the entire collection */ rebuild(deep = false) { if (deep) this.source.rebuild(deep); this.rebuildCache(); } rebuildCache() { this._cachedItems = this.applyFilterAndSort(this._source.items); } applyFilterAndSort(list) { const filtered = this._option.filter === defaultCollectionViewOption.filter ? [...list] : list.filter(this._option.filter); return this.sort === defaultSort ? filtered : filtered.sort(this.sort); } returnItemIfPassesFilter(item) { if (item === void 0) return void 0; return this.filter(item) ? item : void 0; } source_onChange(signal) { this.rebuildCache(); this.notifyChange(signal); } notifyChange(signal) { const changes = filterCollectionChangeDetail(signal.detail, this.filter); const addedCount = changes.added.length; const removedCount = changes.removed.length; const updatedCount = changes.updated.length; if (addedCount === 0 && removedCount === 0 && updatedCount === 0) return; this.notifyObservers(new CollectionChangeSignal(this, changes)); if (addedCount > 0) this.notifyObservers(new CollectionAddSignal(this, changes.added)); if (removedCount > 0) this.notifyObservers(new CollectionRemoveSignal(this, changes.removed)); if (updatedCount > 0) this.notifyObservers(new CollectionUpdateSignal(this, changes.updated)); } get count() { return this._cachedItems.length; } get items() { return this._cachedItems; } exists(item) { if (!this._source.exists(item)) return false; return Boolean(this.returnItemIfPassesFilter(item)); } get source() { return this._source; } get filter() { return this._option.filter; } get sort() { return this._option.sort; } }; //#endregion //#region src/core/CollectionNature.ts let CollectionNature = /* @__PURE__ */ function(CollectionNature$1) { /** * The items in the collection should always be unique, and order does not matter * This option is always performant */ CollectionNature$1["Set"] = "set"; /** * The items in the collection should always preserve the order it is entered in the collection */ CollectionNature$1["Array"] = "array"; return CollectionNature$1; }({}); //#endregion //#region src/core/defaultCollectionOption.ts const defaultCollectionOption = Object.freeze({ nature: CollectionNature.Set }); //#endregion //#region src/core/internals/InternalList.ts /** * A simple list that outputs a new array of the list if * the based array has been modified * * This is an unsupported internal class not meant to be used * beyond internal usage */ var InternalList = class { _isSynced = false; _output = []; constructor(source) { this.source = source; } invalidate() { this._isSynced = false; } get count() { return this.source.length; } get output() { if (!this._isSynced) { this._isSynced = true; this._output = this.source.concat(); } return this._output; } exists(item) { return this.source.includes(item); } add(item) { this.source.push(item); this.invalidate(); } remove(item) { const index = this.source.findIndex((listItem) => listItem === item); if (index >= 0) { this.source.splice(index, 1); this.invalidate(); } } update(newItem, oldItem) { const index = this.source.findIndex((listItem) => listItem === oldItem); if (index >= 0) { this.source[index] = newItem; this.invalidate(); } } moveBefore(item, before) { const itemIndex = this.source.findIndex((listItem) => listItem === item); const beforeIndex = this.source.findIndex((listItem) => listItem === before); if (itemIndex >= 0 && beforeIndex >= 0) { this.source.splice(itemIndex, 1); this.source.splice(beforeIndex, 0, item); this.invalidate(); } } moveAfter(item, after) { const itemIndex = this.source.findIndex((listItem) => listItem === item); const afterIndex = this.source.findIndex((listItem) => listItem === after); if (itemIndex >= 0 && afterIndex >= 0) { this.source.splice(itemIndex, 1); const targetIndex = itemIndex < afterIndex ? afterIndex : afterIndex + 1; this.source.splice(targetIndex, 0, item); this.invalidate(); } } }; //#endregion //#region src/core/internals/InternalSetList.ts /** * An internal data structure that's based on a set * and output a new array if the set has changed * Change of set is notified through invalidate() method * * This is an unsupported internal class not meant to be used * beyond internal usage */ var InternalSetList = class { _isSynced = false; _output = []; constructor(source) { this.source = source; } invalidate() { this._isSynced = false; } get count() { return this.source.size; } get output() { if (!this._isSynced) { this._isSynced = true; this._output = Array.from(this.source); } return this._output; } add(item) { this.source.add(item); this.invalidate(); } exists(item) { return this.source.has(item); } remove(item) { this.source.delete(item); this.invalidate(); } update(newItem, oldItem) { if (this.source.has(oldItem)) { this.source.delete(oldItem); this.source.add(newItem); this.invalidate(); } } moveBefore(_item, _before) { return; } moveAfter(_item, _after) { return; } }; //#endregion //#region src/collections/IndexedCollectionBase.ts var IndexedCollectionBase = class extends SignalObserver { _allItemList = new InternalSetList(/* @__PURE__ */ new Set()); indexes = /* @__PURE__ */ new Set(); _pauseChangeSignal = false; _hasPendingChangeSignal = false; _pendingChange = {}; option; constructor(initialValues, additionalIndexes = [], option = defaultCollectionOption) { super(); this.option = Object.assign({}, defaultCollectionOption, option); this.buildIndexes(additionalIndexes); if (this.option.nature === CollectionNature.Set) this._allItemList = new InternalSetList(/* @__PURE__ */ new Set()); else this._allItemList = new InternalList([]); if (initialValues) this.addRange(initialValues); } rebuild() { this.reindex(); } reindex() { for (const index of this.indexes) index.reset(); const items = this._allItemList.output; for (const item of items) for (const index of this.indexes) index.index(item); } /** * Rebuild indexes * @param indexes * @param autoReindex if true, all items will be reindexed */ buildIndexes(indexes, autoReindex = true) { this.indexes = new Set(indexes); if (autoReindex) this.reindex(); } add(item) { if (this.exists(item)) return false; this._allItemList.add(item); for (const index of this.indexes) index.index(item); this.notifyChange({ added: [item] }); return true; } addRange(items) { let rawItems; if (Array.isArray(items)) rawItems = items; else if (items instanceof Set) rawItems = Array.from(items); else rawItems = items.items; this.pauseChangeSignal(); const result = []; for (const item of rawItems) result.push(this.add(item)); this.resumeChangeSignal(); return result; } exists(item) { return this._allItemList.exists(item); } /** * Remove item from the collection * @param item * @returns */ remove(item) { if (!this.exists(item)) return false; this._allItemList.remove(item); for (const index of this.indexes) index.unIndex(item); this.notifyChange({ removed: [item] }); return true; } update(newItem, oldItem) { if (!this.exists(oldItem)) return false; for (const index of this.indexes) index.unIndex(oldItem); this._allItemList.update(newItem, oldItem); for (const index of this.indexes) index.index(newItem); this.notifyChange({ updated: [{ oldValue: oldItem, newValue: newItem }] }); return true; } /** * Move item before the specified item * @param item The item to move * @param before */ moveBefore(item, before) { this._allItemList.moveBefore(item, before); } /** * Move item after the specified item * @param item The item to move * @param after */ moveAfter(item, after) { this._allItemList.moveAfter(item, after); } get items() { return this._allItemList.output; } get count() { return this._allItemList.count; } notifyChange(change) { if (this._pauseChangeSignal) { this._hasPendingChangeSignal = true; this._pendingChange = mergeCollectionChangeDetail(this._pendingChange, change); return; } const changes = mergeCollectionChangeDetail({}, change); this.notifyObservers(new CollectionChangeSignal(this, changes)); if (changes.added.length > 0) this.notifyObservers(new CollectionAddSignal(this, changes.added)); if (changes.removed.length > 0) this.notifyObservers(new CollectionRemoveSignal(this, changes.removed)); if (changes.updated.length > 0) this.notifyObservers(new CollectionUpdateSignal(this, changes.updated)); } /** * Pause change signal when collection content has changed * This is useful when the collection is undergoing batch changes * that the collection would not cause too many down stream change reaction * during batch update. * * If there are any changes during pause period, resumeChangeEvent * will dispatch change event. */ pauseChangeSignal() { if (!this._pauseChangeSignal) { this._pauseChangeSignal = true; this._hasPendingChangeSignal = false; } } /** * Resume change signal from its pause state * if there are any pending changes, change signal will be notified */ resumeChangeSignal() { if (this._pauseChangeSignal) { this._pauseChangeSignal = false; if (this._hasPendingChangeSignal) { this._hasPendingChangeSignal = false; this.notifyChange(this._pendingChange); this._pendingChange = {}; } } } }; //#endregion //#region src/indexes/IndexBase.ts const emptyArray = Object.freeze([]); var IndexBase = class { _keyFns; option; internalMap = /* @__PURE__ */ new Map(); constructor(keyFns, option = defaultCollectionOption) { this._keyFns = keyFns; this.option = Object.freeze(Object.assign({}, defaultCollectionOption, option)); } index(item) { const keys = this.getKeys(item); const leafMaps = this.getLeafMaps(keys); const lastIndex = keys.length - 1; const lastKeys = keys[lastIndex]; let added = false; const isUsingSet = this.option.nature === CollectionNature.Set; for (const leafMap of leafMaps) for (const key of lastKeys) { const result = addItemToMap(key, item, leafMap, isUsingSet); added = added || result; } return added; } unIndex(item) { const keys = this.getKeys(item); const leafMaps = this.getLeafMaps(keys); const lastKeys = keys[keys.length - 1]; let removed = false; for (const leafMap of leafMaps) for (const key of lastKeys) { const result = removeItemFromMap(key, item, leafMap); removed = removed || result; } return removed; } getValueInternal(keys) { const convertedKeys = keys.map((k) => [k]); const leafMaps = this.getLeafMaps(convertedKeys); const lastKey = keys[keys.length - 1]; const values = leafMaps[0]?.get(lastKey); if (values == null) return emptyArray; return values.output; } getKeys(item) { return this._keyFns.map((keyFn) => { return keyFn.isMultiple ? keyFn(item) : [keyFn(item)]; }); } getLeafMaps(keys) { if (keys.length === 1) return [this.internalMap]; let currentLevelMap = [this.internalMap]; for (let i = 0; i < keys.length - 1; i++) { const maps = []; for (const key of keys[i]) for (const map of currentLevelMap) { if (!map.has(key)) map.set(key, /* @__PURE__ */ new Map()); maps.push(map.get(key)); } currentLevelMap = maps; } return currentLevelMap; } reset() { this.internalMap = /* @__PURE__ */ new Map(); } }; function getNewInternalList(isUsingSet) { return isUsingSet ? new InternalSetList(/* @__PURE__ */ new Set()) : new InternalList([]); } function addItemToMap(key, item, map, isUsingSet) { if (!map.has(key)) { const content = getNewInternalList(isUsingSet); content.add(item); map.set(key, content); return true; } const items = map.get(key); if (!items.exists(item)) { items.add(item); return true; } return false; } function removeItemFromMap(key, item, map) { const items = map.get(key); if (items.exists(item)) { items.remove(item); return true; } return false; } //#endregion //#region src/indexes/CollectionIndex.ts var CollectionIndex = class extends IndexBase { constructor(keyFn, option = defaultCollectionOption) { super(keyFn, option); } getValue(...keys) { return super.getValueInternal(keys); } }; //#endregion //#region src/collections/PrimaryKeyCollection.ts /** * A collection where every item contains a unique identifier key (aka primary key) */ var PrimaryKeyCollection = class extends IndexedCollectionBase { idIndex; constructor(primaryKeyExtract, initialValues, additionalIndexes = [], option = defaultCollectionOption) { super(void 0, void 0, option); this.primaryKeyExtract = primaryKeyExtract; this.idIndex = new CollectionIndex([primaryKeyExtract]); this.buildIndexes([this.idIndex, ...additionalIndexes]); if (initialValues) this.addRange(initialValues); } buildIndexes(indexes, autoReindex) { const combinedIndex = []; if (this.idIndex != null) combinedIndex.push(this.idIndex); if (indexes != null && indexes.length > 0) combinedIndex.push(...indexes); super.buildIndexes(combinedIndex, autoReindex); } exists(item) { const key = this.primaryKeyExtract(item); return Boolean(this.byPrimaryKey(key)); } /** * Get the item by its primary key * @param keyValue * @returns */ byPrimaryKey(keyValue) { return this.idIndex.getValue(keyValue)[0]; } update(newItem) { const key = this.primaryKeyExtract(newItem); const oldItem = this.byPrimaryKey(key); if (oldItem) return super.update(newItem, oldItem); return false; } }; //#endregion export { CollectionAddSignal, CollectionChangeSignal, CollectionIndex, CollectionNature, CollectionRemoveSignal, CollectionUpdateSignal, CollectionViewBase, IndexBase, IndexedCollectionBase, PrimaryKeyCollection, buildMultipleKeyExtract, defaultCollectionOption, defaultFilter as defaultCollectionViewFilter, defaultCollectionViewOption, defaultSort as defaultCollectionViewSort };