UNPKG

@signaldb/core

Version:

SignalDB is a client-side database that provides a simple MongoDB-like interface to the data with first-class typescript support to achieve an optimistic UI. Data persistence can be achieved by using storage providers that store the data through a JSON in

69 lines (68 loc) 2.4 kB
import get from "./index2.mjs"; import serializeValue from "./index15.mjs"; import createIndexProvider from "./index19.mjs"; import getMatchingKeys from "./index21.mjs"; //#region src/Collection/createIndex.ts /** * creates an index for a specific field but uses an external map to store the index * @param field name of the field * @param index the external map to use for the index * @returns an index provider to pass to the `indices` option of the collection constructor */ function createExternalIndex(field, index) { return createIndexProvider({ query(selector) { if (!Object.hasOwnProperty.call(selector, field)) return { matched: false }; const fieldSelector = selector[field]; const filteresForNull = fieldSelector == null || fieldSelector.$exists === false; const keys = filteresForNull ? { include: null, exclude: [...index.keys()].filter((key) => key != null) } : getMatchingKeys(field, selector); if (keys.include == null && keys.exclude == null) return { matched: false }; let includedPositions = []; if (keys.include == null) for (const set of index.values()) for (const pos of set) includedPositions.push(pos); else for (const key of keys.include) { const posSet = index.get(key); if (posSet) for (const pos of posSet) includedPositions.push(pos); } if (keys.exclude != null) { const excludeSet = /* @__PURE__ */ new Set(); for (const key of keys.exclude) { const posSet = index.get(key); if (posSet) for (const pos of posSet) excludeSet.add(pos); } includedPositions = includedPositions.filter((pos) => !excludeSet.has(pos)); } return { matched: true, positions: includedPositions, fields: [field], keepSelector: filteresForNull }; }, rebuild() {} }); } /** * creates an index for a specific field * @param field name of the field * @returns an index provider to pass to the `indices` option of the collection constructor */ function createIndex(field) { const index = /* @__PURE__ */ new Map(); return { ...createExternalIndex(field, index), rebuild(items) { index.clear(); items.forEach((item, i) => { const value = serializeValue(get(item, field)); const current = index.get(value) || /* @__PURE__ */ new Set(); current.add(i); index.set(value, current); }); } }; } //#endregion export { createExternalIndex, createIndex as default };