@devisfuture/mega-collection 2.4.3 → 2.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,54 +1,4 @@
1
- import { S as State } from '../State-2vKzwNrQ.mjs';
2
- import { C as CollectionItem, U as UpdateDescriptor, d as SortDescriptor } from '../types-DONld7xY.mjs';
3
- export { e as SortDirection } from '../types-DONld7xY.mjs';
4
-
5
- interface SortEngineOptions<T extends CollectionItem = CollectionItem> {
6
- data?: T[];
7
- fields?: (keyof T & string)[];
8
- }
9
-
10
- declare class SortEngine<T extends CollectionItem> {
11
- private readonly state;
12
- private readonly namespace;
13
- constructor(options?: SortEngineOptions<T> & {
14
- state?: State<T>;
15
- });
16
- private get dataset();
17
- private get runtime();
18
- private get cache();
19
- private get indexedFields();
20
- private shouldDeferMutationCacheUpdates;
21
- private invalidateCachedIndexes;
22
- private rebuildConfiguredIndexes;
23
- private buildIndexForDataset;
24
- private buildIndexFromData;
25
- clearIndexes(): this;
26
- clearData(): this;
27
- data(data: T[]): this;
28
- add(items: T[]): this;
29
- update(descriptor: UpdateDescriptor<T>): this;
30
- private applyAddedItems;
31
- getOriginData(): T[];
32
- private handleStateMutation;
33
- sort(descriptors: SortDescriptor<T>[]): T[];
34
- sort(data: T[], descriptors: SortDescriptor<T>[], inPlace?: boolean): T[];
35
- private sortNumericFastPath;
36
- private sortMultiField;
37
- private sortTieGroups;
38
- private materializeItemsFromIndexes;
39
- private getCachedSortedItems;
40
- private shouldMaintainIncrementally;
41
- private hasDuplicateValuesForIndexes;
42
- private compareIndexesByField;
43
- private applyUpdatedItem;
44
- private updateCachedIndexForUpdatedItem;
45
- private updateCachedIndexForAddedItems;
46
- private applyRemovedItem;
47
- private applyRemovedItemsBatch;
48
- private updateCachedIndexForRemovedItem;
49
- private updateUniqueCachedIndexForRemovedItem;
50
- private updateUniqueCachedIndexForRemovedItems;
51
- private buildComparator;
52
- }
53
-
54
- export { CollectionItem, SortDescriptor, SortEngine, type SortEngineOptions };
1
+ export { SortEngine } from "./sorter";
2
+ export type { SortEngineOptions } from "./types";
3
+ export type { CollectionItem, SortDescriptor, SortDirection } from "../types";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -1 +1,416 @@
1
- import {a,b as b$1}from'../chunk-MB56OSRQ.mjs';var f=class p extends Error{constructor(e){super(e),this.name="SortEngineError";}static missingDatasetForSort(){return new p("SortEngine: no dataset in memory.")}};var b="deferSortMutationCacheUpdates";function x(p,e){for(let r=0;r<e;r++){let n=p[r];if(n!==n>>>0)return false}return true}function I(p,e,r){let n=new Uint32Array(r),t=new Uint32Array(65536);for(let s=0;s<r;s++)t[e[p[s]]&65535]++;let i=0;for(let s=0;s<65536;s++){let a=t[s];t[s]=i,i+=a;}for(let s=0;s<r;s++){let a=e[p[s]]&65535;n[t[a]++]=p[s];}t.fill(0);for(let s=0;s<r;s++)t[e[n[s]]>>>16&65535]++;i=0;for(let s=0;s<65536;s++){let a=t[s];t[s]=i,i+=a;}for(let s=0;s<r;s++){let a=e[n[s]]>>>16&65535;p[t[a]++]=n[s];}}var S=()=>({indexedFields:new Set,cache:new Map});var g=class{constructor(e={}){if(this.state=e.state??new a(e.data??[]),this.namespace=this.state.createNamespace("sort"),this.state.subscribe(r=>this.handleStateMutation(r)),e.fields?.length){for(let r of e.fields)this.indexedFields.add(r);this.dataset.length>0&&this.rebuildConfiguredIndexes();}}get dataset(){return this.state.getOriginData()}get runtime(){return this.state.getOrCreateScopedValue(this.namespace,"runtime",S)}get cache(){return this.runtime.cache}get indexedFields(){return this.runtime.indexedFields}shouldDeferMutationCacheUpdates(){return this.state.getScopedValue(b$1,b)===true}invalidateCachedIndexes(){for(let e of this.indexedFields)this.cache.delete(e);}rebuildConfiguredIndexes(){this.cache.clear();for(let e of this.indexedFields)this.buildIndexForDataset(e);}buildIndexForDataset(e){this.dataset.length&&this.buildIndexFromData(this.dataset,e);}buildIndexFromData(e,r){let n=e.length,t=new Uint32Array(n);for(let o=0;o<n;o++)t[o]=o;let i=0;for(;i<n&&e[i][r]==null;)i++;if(i<n&&typeof e[i][r]=="number"){let o=new Float64Array(n);for(let l=0;l<n;l++)o[l]=e[l][r];x(o,n)?I(t,o,n):t.sort((l,d)=>o[l]-o[d]);}else {let o=new Array(n);for(let l=0;l<n;l++)o[l]=e[l][r];t.sort((l,d)=>{let c=o[l],h=o[d];return c<h?-1:c>h?1:0});}let a=new Uint32Array(n);for(let o=0;o<n;o++)a[t[o]]=o;this.cache.set(r,{indexes:t,reverseIndex:a,ascItems:null,descItems:null,hasDuplicateValues:this.hasDuplicateValuesForIndexes(e,t,r),version:this.state.getMutationVersion()});}clearIndexes(){return this.cache.clear(),this}clearData(){return this.state.clearData(),this}data(e){return this.state.data(e),this}add(e){return this.state.add(e),this}update(e){return this.state.update(e),this}applyAddedItems(e,r){if(r===0)return this;if(this.shouldDeferMutationCacheUpdates())return this.invalidateCachedIndexes(),this;for(let n of this.indexedFields){let t=this.cache.get(n);if(t){if(!this.shouldMaintainIncrementally(t)){this.cache.delete(n);continue}this.updateCachedIndexForAddedItems(n,e,r);}}return this}getOriginData(){return this.state.getOriginData()}handleStateMutation(e){switch(e.type){case "add":this.applyAddedItems(e.startIndex,e.items.length);return;case "update":this.applyUpdatedItem(e.index,e.previousItem,e.nextItem);return;case "data":this.rebuildConfiguredIndexes();return;case "clearData":this.cache.clear();return;case "remove":this.applyRemovedItem(e.removedIndex,e.movedFromIndex);return;case "removeMany":this.applyRemovedItemsBatch(e.entries);return}}sort(e,r,n=false){let t=r===void 0,i,s;if(t){if(!this.dataset.length)throw f.missingDatasetForSort();i=this.dataset,s=e;}else i=e,s=r;if(s.length===0||i.length===0)return i;if(s.length===1){let{field:a,direction:o}=s[0];if(t&&this.indexedFields.has(a)){let l=this.cache.get(a),d=this.state.getMutationVersion();return (!l||l.version!==d)&&(this.buildIndexForDataset(a),l=this.cache.get(a)),this.getCachedSortedItems(l,o)}return this.sortNumericFastPath(i,a,o,n)}return this.sortMultiField(i,s,n,t)}sortNumericFastPath(e,r,n,t){if(e.length===0||typeof e[0][r]!="number"){let o=t?e:e.slice();return o.sort((l,d)=>{let c=l[r],h=d[r],u=c<h?-1:c>h?1:0;return n==="asc"?u:-u}),o}let i=e.length,s=new Float64Array(i);for(let o=0;o<i;o++)s[o]=e[o][r];let a=new Uint32Array(i);for(let o=0;o<i;o++)a[o]=o;return x(s,i)?I(a,s,i):a.sort((o,l)=>s[o]-s[l]),this.materializeItemsFromIndexes(e,a,n)}sortMultiField(e,r,n,t){let[i,...s]=r;if(t&&this.indexedFields.has(i.field)){let l=this.cache.get(i.field),d=this.state.getMutationVersion();(!l||l.version!==d)&&(this.buildIndexForDataset(i.field),l=this.cache.get(i.field));let c=l.hasDuplicateValues?this.getCachedSortedItems(l,i.direction).slice():this.getCachedSortedItems(l,i.direction);return l.hasDuplicateValues?this.sortTieGroups(c,i.field,s):c}let a=n?e:e.slice(),o=this.buildComparator(r);return a.sort(o),a}sortTieGroups(e,r,n){if(n.length===0)return e;let t=this.buildComparator(n),i=e.length,s=0;for(;s<i;){let a=s+1,o=e[s][r];for(;a<i&&e[a][r]===o;)a++;if(a-s>1){let l=e.slice(s,a);l.sort(t);for(let d=s;d<a;d++)e[d]=l[d-s];}s=a;}return e}materializeItemsFromIndexes(e,r,n){let t=r.length,i=new Array(t);if(n==="asc"){for(let s=0;s<t;s++)i[s]=e[r[s]];return i}for(let s=0;s<t;s++)i[s]=e[r[t-1-s]];return i}getCachedSortedItems(e,r){if(r==="asc")return e.ascItems===null&&(e.ascItems=this.materializeItemsFromIndexes(this.dataset,e.indexes,"asc")),e.ascItems;if(e.descItems!==null)return e.descItems;let n=this.getCachedSortedItems(e,"asc");return e.descItems=n.slice().reverse(),e.descItems}shouldMaintainIncrementally(e){return e.ascItems!==null||e.descItems!==null}hasDuplicateValuesForIndexes(e,r,n){for(let t=1;t<r.length;t++)if(e[r[t-1]][n]===e[r[t]][n])return true;return false}compareIndexesByField(e,r,n){let t=this.dataset[r][e],i=this.dataset[n][e];if(typeof t=="number"&&typeof i=="number"){let s=t-i;if(s!==0)return s}else {if(t<i)return -1;if(t>i)return 1}return r-n}applyUpdatedItem(e,r,n){if(this.shouldDeferMutationCacheUpdates()){this.invalidateCachedIndexes();return}for(let t of this.indexedFields){if(r[t]===n[t])continue;let i=this.cache.get(t);if(i){if(!this.shouldMaintainIncrementally(i)){this.cache.delete(t);continue}this.updateCachedIndexForUpdatedItem(t,e);}}}updateCachedIndexForUpdatedItem(e,r){let n=this.cache.get(e);if(!n)return;let{indexes:t,reverseIndex:i}=n,s=t.length,a=i[r];if(a>=s||t[a]!==r){this.cache.delete(e);return}t.copyWithin(a,a+1);let o=s-1,l=0,d=o;for(;l<d;){let m=l+d>>1;this.compareIndexesByField(e,t[m],r)<=0?l=m+1:d=m;}let c=l;t.copyWithin(c+1,c,o),t[c]=r,n.ascItems!==null&&(n.ascItems.copyWithin(a,a+1),n.ascItems.copyWithin(c+1,c,o),n.ascItems[c]=this.dataset[r]);let h=Math.min(a,c),u=Math.max(a,c);for(let m=h;m<=u;m++)i[t[m]]=m;if(n.descItems=null,!n.hasDuplicateValues){let m=c>0?t[c-1]:-1,v=c+1<s?t[c+1]:-1;n.hasDuplicateValues=m!==-1&&this.dataset[m][e]===this.dataset[r][e]||v!==-1&&this.dataset[v][e]===this.dataset[r][e];}n.version=this.state.getMutationVersion();}updateCachedIndexForAddedItems(e,r,n){let t=this.cache.get(e);if(!t)return;let i=new Array(n);for(let u=0;u<n;u++)i[u]=r+u;i.sort((u,m)=>this.compareIndexesByField(e,u,m));let s=new Uint32Array(t.indexes.length+n),a=-1,o=t.hasDuplicateValues,l=0,d=0,c=0;for(;l<t.indexes.length&&d<i.length;){let u=this.compareIndexesByField(e,t.indexes[l],i[d])<=0?t.indexes[l++]:i[d++];s[c]=u,!o&&a!==-1&&this.dataset[a][e]===this.dataset[u][e]&&(o=true),a=u,c+=1;}for(;l<t.indexes.length;){let u=t.indexes[l++];s[c]=u,!o&&a!==-1&&this.dataset[a][e]===this.dataset[u][e]&&(o=true),a=u,c+=1;}for(;d<i.length;){let u=i[d++];s[c]=u,!o&&a!==-1&&this.dataset[a][e]===this.dataset[u][e]&&(o=true),a=u,c+=1;}let h=new Uint32Array(s.length);for(let u=0;u<s.length;u++)h[s[u]]=u;t.indexes=s,t.reverseIndex=h,t.ascItems=t.ascItems?this.materializeItemsFromIndexes(this.dataset,s,"asc"):null,t.descItems=null,t.hasDuplicateValues=o,t.version=this.state.getMutationVersion();}applyRemovedItem(e,r){if(this.shouldDeferMutationCacheUpdates()){this.invalidateCachedIndexes();return}for(let n of this.indexedFields){let t=this.cache.get(n);if(t){if(!this.shouldMaintainIncrementally(t)){this.cache.delete(n);continue}this.updateCachedIndexForRemovedItem(n,e,r);}}}applyRemovedItemsBatch(e){if(this.shouldDeferMutationCacheUpdates()){this.invalidateCachedIndexes();return}for(let r of this.indexedFields){let n=this.cache.get(r);if(n){if(!this.shouldMaintainIncrementally(n)){this.cache.delete(r);continue}if(!n.hasDuplicateValues){this.updateUniqueCachedIndexForRemovedItems(n,e),n.version=this.state.getMutationVersion();continue}this.cache.delete(r);}}}updateCachedIndexForRemovedItem(e,r,n){let t=this.cache.get(e);if(!t)return;if(!t.hasDuplicateValues){this.updateUniqueCachedIndexForRemovedItem(t,r,n),t.version=this.state.getMutationVersion();return}let i=[];for(let o=0;o<t.indexes.length;o++){let l=t.indexes[o];l===r||l===n||i.push(l);}if(n!==null&&n!==r){let o=0,l=i.length;for(;o<l;){let d=o+l>>1;this.compareIndexesByField(e,i[d],r)<=0?o=d+1:l=d;}i.splice(o,0,r);}let s=Uint32Array.from(i),a=new Uint32Array(this.dataset.length);for(let o=0;o<s.length;o++){let l=s[o];a[l]=o;}t.indexes=s,t.reverseIndex=a,t.ascItems=t.ascItems?this.materializeItemsFromIndexes(this.dataset,s,"asc"):null,t.descItems=null,t.hasDuplicateValues=t.hasDuplicateValues?this.hasDuplicateValuesForIndexes(this.dataset,s,e):false,t.version=this.state.getMutationVersion();}updateUniqueCachedIndexForRemovedItem(e,r,n){let t=e.indexes.length-1,i=new Uint32Array(t),s=new Uint32Array(this.dataset.length),a=e.ascItems!==null?new Array(t):null,o=0;for(let l=0;l<e.indexes.length;l++){let d=e.indexes[l];if(d===r)continue;let c=n!==null&&d===n?r:d;i[o]=c,s[c]=o,a!==null&&(a[o]=this.dataset[c]),o+=1;}e.indexes=i,e.reverseIndex=s,e.ascItems=a,e.descItems=null;}updateUniqueCachedIndexForRemovedItems(e,r){let n=e.indexes.length,t=new Uint32Array(n),i=new Int32Array(n);for(let c=0;c<n;c++)t[c]=c,i[c]=-1;let s=n;for(let c=0;c<r.length;c++){let h=r[c];h.movedFromIndex!==null&&(t[h.removedIndex]=t[h.movedFromIndex]),s-=1;}let a=new Uint32Array(s),o=new Uint32Array(s),l=e.ascItems!==null?new Array(s):null;for(let c=0;c<s;c++)i[t[c]]=c;let d=0;for(let c=0;c<e.indexes.length;c++){let h=e.indexes[c],u=i[h];u!==-1&&(a[d]=u,o[u]=d,l!==null&&(l[d]=this.dataset[u]),d+=1);}e.indexes=a,e.reverseIndex=o,e.ascItems=l,e.descItems=null;}buildComparator(e){let r=e.map(({field:i})=>i),n=e.map(({direction:i})=>i==="asc"?1:-1),t=r.length;return (i,s)=>{for(let a=0;a<t;a++){let o=r[a],l=i[o],d=s[o];if(l<d)return -n[a];if(l>d)return n[a]}return 0}}};export{g as SortEngine};
1
+ import { a as e, i as t, r as n } from "../chunk-BJZg_1dI.mjs";
2
+ //#region src/sort/errors.ts
3
+ var r = class e extends Error {
4
+ constructor(e) {
5
+ super(e), this.name = "SortEngineError";
6
+ }
7
+ static missingDatasetForSort() {
8
+ return new e("SortEngine: no dataset in memory.");
9
+ }
10
+ };
11
+ //#endregion
12
+ //#region src/sort/utils.ts
13
+ function i(e, t) {
14
+ for (let n = 0; n < t; n++) {
15
+ let t = e[n];
16
+ if (t !== t >>> 0) return !1;
17
+ }
18
+ return !0;
19
+ }
20
+ function a(e, t, n) {
21
+ let r = new Uint32Array(n), i = new Uint32Array(65536);
22
+ for (let r = 0; r < n; r++) i[t[e[r]] & 65535]++;
23
+ let a = 0;
24
+ for (let e = 0; e < 65536; e++) {
25
+ let t = i[e];
26
+ i[e] = a, a += t;
27
+ }
28
+ for (let a = 0; a < n; a++) {
29
+ let n = t[e[a]] & 65535;
30
+ r[i[n]++] = e[a];
31
+ }
32
+ i.fill(0);
33
+ for (let e = 0; e < n; e++) i[t[r[e]] >>> 16 & 65535]++;
34
+ a = 0;
35
+ for (let e = 0; e < 65536; e++) {
36
+ let t = i[e];
37
+ i[e] = a, a += t;
38
+ }
39
+ for (let a = 0; a < n; a++) {
40
+ let n = t[r[a]] >>> 16 & 65535;
41
+ e[i[n]++] = r[a];
42
+ }
43
+ }
44
+ var o = () => ({
45
+ indexedFields: /* @__PURE__ */ new Set(),
46
+ cache: /* @__PURE__ */ new Map()
47
+ }), s = class {
48
+ constructor(t = {}) {
49
+ if (this.state = t.state ?? new e(t.data ?? []), this.namespace = this.state.createNamespace("sort"), this.state.subscribe((e) => this.handleStateMutation(e)), t.fields?.length) {
50
+ for (let e of t.fields) this.indexedFields.add(e);
51
+ this.dataset.length > 0 && this.rebuildConfiguredIndexes();
52
+ }
53
+ }
54
+ get dataset() {
55
+ return this.state.getOriginData();
56
+ }
57
+ get runtime() {
58
+ return this.state.getOrCreateScopedValue(this.namespace, "runtime", o);
59
+ }
60
+ get cache() {
61
+ return this.runtime.cache;
62
+ }
63
+ get indexedFields() {
64
+ return this.runtime.indexedFields;
65
+ }
66
+ shouldDeferMutationCacheUpdates() {
67
+ return this.state.getScopedValue(t, n) === !0;
68
+ }
69
+ invalidateCachedIndexes() {
70
+ for (let e of this.indexedFields) this.cache.delete(e);
71
+ }
72
+ rebuildConfiguredIndexes() {
73
+ this.cache.clear();
74
+ for (let e of this.indexedFields) this.buildIndexForDataset(e);
75
+ }
76
+ buildIndexForDataset(e) {
77
+ this.dataset.length && this.buildIndexFromData(this.dataset, e);
78
+ }
79
+ buildIndexFromData(e, t) {
80
+ let n = e.length, r = new Uint32Array(n);
81
+ for (let e = 0; e < n; e++) r[e] = e;
82
+ let o = 0;
83
+ for (; o < n && e[o][t] == null;) o++;
84
+ if (o < n && typeof e[o][t] == "number") {
85
+ let o = new Float64Array(n);
86
+ for (let r = 0; r < n; r++) o[r] = e[r][t];
87
+ i(o, n) ? a(r, o, n) : r.sort((e, t) => o[e] - o[t]);
88
+ } else {
89
+ let i = Array(n);
90
+ for (let r = 0; r < n; r++) i[r] = e[r][t];
91
+ r.sort((e, t) => {
92
+ let n = i[e], r = i[t];
93
+ return n < r ? -1 : n > r ? 1 : 0;
94
+ });
95
+ }
96
+ let s = new Uint32Array(n);
97
+ for (let e = 0; e < n; e++) s[r[e]] = e;
98
+ this.cache.set(t, {
99
+ indexes: r,
100
+ reverseIndex: s,
101
+ ascItems: null,
102
+ descItems: null,
103
+ hasDuplicateValues: this.hasDuplicateValuesForIndexes(e, r, t),
104
+ version: this.state.getMutationVersion()
105
+ });
106
+ }
107
+ clearIndexes() {
108
+ return this.cache.clear(), this;
109
+ }
110
+ clearData() {
111
+ return this.state.clearData(), this;
112
+ }
113
+ data(e) {
114
+ return this.state.data(e), this;
115
+ }
116
+ add(e) {
117
+ return this.state.add(e), this;
118
+ }
119
+ update(e) {
120
+ return this.state.update(e), this;
121
+ }
122
+ applyAddedItems(e, t) {
123
+ if (t === 0) return this;
124
+ if (this.shouldDeferMutationCacheUpdates()) return this.invalidateCachedIndexes(), this;
125
+ for (let n of this.indexedFields) {
126
+ let r = this.cache.get(n);
127
+ if (r) {
128
+ if (!this.shouldMaintainIncrementally(r)) {
129
+ this.cache.delete(n);
130
+ continue;
131
+ }
132
+ this.updateCachedIndexForAddedItems(n, e, t);
133
+ }
134
+ }
135
+ return this;
136
+ }
137
+ getOriginData() {
138
+ return this.state.getOriginData();
139
+ }
140
+ handleStateMutation(e) {
141
+ switch (e.type) {
142
+ case "add":
143
+ this.applyAddedItems(e.startIndex, e.items.length);
144
+ return;
145
+ case "update":
146
+ this.applyUpdatedItem(e.index, e.previousItem, e.nextItem);
147
+ return;
148
+ case "data":
149
+ this.rebuildConfiguredIndexes();
150
+ return;
151
+ case "clearData":
152
+ this.cache.clear();
153
+ return;
154
+ case "remove":
155
+ this.applyRemovedItem(e.removedIndex, e.movedFromIndex);
156
+ return;
157
+ case "removeMany":
158
+ this.applyRemovedItemsBatch(e.entries);
159
+ return;
160
+ }
161
+ }
162
+ sort(e, t, n = !1) {
163
+ let i = t === void 0, a, o;
164
+ if (i) {
165
+ if (!this.dataset.length) throw r.missingDatasetForSort();
166
+ a = this.dataset, o = e;
167
+ } else a = e, o = t;
168
+ if (o.length === 0 || a.length === 0) return a;
169
+ if (o.length === 1) {
170
+ let { field: e, direction: t } = o[0];
171
+ if (i && this.indexedFields.has(e)) {
172
+ let n = this.cache.get(e), r = this.state.getMutationVersion();
173
+ return (!n || n.version !== r) && (this.buildIndexForDataset(e), n = this.cache.get(e)), this.getCachedSortedItems(n, t);
174
+ }
175
+ return this.sortNumericFastPath(a, e, t, n);
176
+ }
177
+ return this.sortMultiField(a, o, n, i);
178
+ }
179
+ sortNumericFastPath(e, t, n, r) {
180
+ if (e.length === 0 || typeof e[0][t] != "number") {
181
+ let i = r ? e : e.slice();
182
+ return i.sort((e, r) => {
183
+ let i = e[t], a = r[t], o = i < a ? -1 : i > a ? 1 : 0;
184
+ return n === "asc" ? o : -o;
185
+ }), i;
186
+ }
187
+ let o = e.length, s = new Float64Array(o);
188
+ for (let n = 0; n < o; n++) s[n] = e[n][t];
189
+ let c = new Uint32Array(o);
190
+ for (let e = 0; e < o; e++) c[e] = e;
191
+ return i(s, o) ? a(c, s, o) : c.sort((e, t) => s[e] - s[t]), this.materializeItemsFromIndexes(e, c, n);
192
+ }
193
+ sortMultiField(e, t, n, r) {
194
+ let [i, ...a] = t;
195
+ if (r && this.indexedFields.has(i.field)) {
196
+ let e = this.cache.get(i.field), t = this.state.getMutationVersion();
197
+ (!e || e.version !== t) && (this.buildIndexForDataset(i.field), e = this.cache.get(i.field));
198
+ let n = e.hasDuplicateValues ? this.getCachedSortedItems(e, i.direction).slice() : this.getCachedSortedItems(e, i.direction);
199
+ return e.hasDuplicateValues ? this.sortTieGroups(n, i.field, a) : n;
200
+ }
201
+ let o = n ? e : e.slice(), s = this.buildComparator(t);
202
+ return o.sort(s), o;
203
+ }
204
+ sortTieGroups(e, t, n) {
205
+ if (n.length === 0) return e;
206
+ let r = this.buildComparator(n), i = e.length, a = 0;
207
+ for (; a < i;) {
208
+ let n = a + 1, o = e[a][t];
209
+ for (; n < i && e[n][t] === o;) n++;
210
+ if (n - a > 1) {
211
+ let t = e.slice(a, n);
212
+ t.sort(r);
213
+ for (let r = a; r < n; r++) e[r] = t[r - a];
214
+ }
215
+ a = n;
216
+ }
217
+ return e;
218
+ }
219
+ materializeItemsFromIndexes(e, t, n) {
220
+ let r = t.length, i = Array(r);
221
+ if (n === "asc") {
222
+ for (let n = 0; n < r; n++) i[n] = e[t[n]];
223
+ return i;
224
+ }
225
+ for (let n = 0; n < r; n++) i[n] = e[t[r - 1 - n]];
226
+ return i;
227
+ }
228
+ getCachedSortedItems(e, t) {
229
+ return t === "asc" ? (e.ascItems === null && (e.ascItems = this.materializeItemsFromIndexes(this.dataset, e.indexes, "asc")), e.ascItems) : (e.descItems === null && (e.descItems = this.getCachedSortedItems(e, "asc").slice().reverse()), e.descItems);
230
+ }
231
+ shouldMaintainIncrementally(e) {
232
+ return e.ascItems !== null || e.descItems !== null;
233
+ }
234
+ hasDuplicateValuesForIndexes(e, t, n) {
235
+ for (let r = 1; r < t.length; r++) if (e[t[r - 1]][n] === e[t[r]][n]) return !0;
236
+ return !1;
237
+ }
238
+ compareIndexesByField(e, t, n) {
239
+ let r = this.dataset[t][e], i = this.dataset[n][e];
240
+ if (typeof r == "number" && typeof i == "number") {
241
+ let e = r - i;
242
+ if (e !== 0) return e;
243
+ } else {
244
+ if (r < i) return -1;
245
+ if (r > i) return 1;
246
+ }
247
+ return t - n;
248
+ }
249
+ applyUpdatedItem(e, t, n) {
250
+ if (this.shouldDeferMutationCacheUpdates()) {
251
+ this.invalidateCachedIndexes();
252
+ return;
253
+ }
254
+ for (let r of this.indexedFields) {
255
+ if (t[r] === n[r]) continue;
256
+ let i = this.cache.get(r);
257
+ if (i) {
258
+ if (!this.shouldMaintainIncrementally(i)) {
259
+ this.cache.delete(r);
260
+ continue;
261
+ }
262
+ this.updateCachedIndexForUpdatedItem(r, e);
263
+ }
264
+ }
265
+ }
266
+ updateCachedIndexForUpdatedItem(e, t) {
267
+ let n = this.cache.get(e);
268
+ if (!n) return;
269
+ let { indexes: r, reverseIndex: i } = n, a = r.length, o = i[t];
270
+ if (o >= a || r[o] !== t) {
271
+ this.cache.delete(e);
272
+ return;
273
+ }
274
+ r.copyWithin(o, o + 1);
275
+ let s = a - 1, c = 0, l = s;
276
+ for (; c < l;) {
277
+ let n = c + l >> 1;
278
+ this.compareIndexesByField(e, r[n], t) <= 0 ? c = n + 1 : l = n;
279
+ }
280
+ let u = c;
281
+ r.copyWithin(u + 1, u, s), r[u] = t, n.ascItems !== null && (n.ascItems.copyWithin(o, o + 1), n.ascItems.copyWithin(u + 1, u, s), n.ascItems[u] = this.dataset[t]);
282
+ let d = Math.min(o, u), f = Math.max(o, u);
283
+ for (let e = d; e <= f; e++) i[r[e]] = e;
284
+ if (n.descItems = null, !n.hasDuplicateValues) {
285
+ let i = u > 0 ? r[u - 1] : -1, o = u + 1 < a ? r[u + 1] : -1;
286
+ n.hasDuplicateValues = i !== -1 && this.dataset[i][e] === this.dataset[t][e] || o !== -1 && this.dataset[o][e] === this.dataset[t][e];
287
+ }
288
+ n.version = this.state.getMutationVersion();
289
+ }
290
+ updateCachedIndexForAddedItems(e, t, n) {
291
+ let r = this.cache.get(e);
292
+ if (!r) return;
293
+ let i = Array(n);
294
+ for (let e = 0; e < n; e++) i[e] = t + e;
295
+ i.sort((t, n) => this.compareIndexesByField(e, t, n));
296
+ let a = new Uint32Array(r.indexes.length + n), o = -1, s = r.hasDuplicateValues, c = 0, l = 0, u = 0;
297
+ for (; c < r.indexes.length && l < i.length;) {
298
+ let t = this.compareIndexesByField(e, r.indexes[c], i[l]) <= 0 ? r.indexes[c++] : i[l++];
299
+ a[u] = t, !s && o !== -1 && this.dataset[o][e] === this.dataset[t][e] && (s = !0), o = t, u += 1;
300
+ }
301
+ for (; c < r.indexes.length;) {
302
+ let t = r.indexes[c++];
303
+ a[u] = t, !s && o !== -1 && this.dataset[o][e] === this.dataset[t][e] && (s = !0), o = t, u += 1;
304
+ }
305
+ for (; l < i.length;) {
306
+ let t = i[l++];
307
+ a[u] = t, !s && o !== -1 && this.dataset[o][e] === this.dataset[t][e] && (s = !0), o = t, u += 1;
308
+ }
309
+ let d = new Uint32Array(a.length);
310
+ for (let e = 0; e < a.length; e++) d[a[e]] = e;
311
+ r.indexes = a, r.reverseIndex = d, r.ascItems = r.ascItems ? this.materializeItemsFromIndexes(this.dataset, a, "asc") : null, r.descItems = null, r.hasDuplicateValues = s, r.version = this.state.getMutationVersion();
312
+ }
313
+ applyRemovedItem(e, t) {
314
+ if (this.shouldDeferMutationCacheUpdates()) {
315
+ this.invalidateCachedIndexes();
316
+ return;
317
+ }
318
+ for (let n of this.indexedFields) {
319
+ let r = this.cache.get(n);
320
+ if (r) {
321
+ if (!this.shouldMaintainIncrementally(r)) {
322
+ this.cache.delete(n);
323
+ continue;
324
+ }
325
+ this.updateCachedIndexForRemovedItem(n, e, t);
326
+ }
327
+ }
328
+ }
329
+ applyRemovedItemsBatch(e) {
330
+ if (this.shouldDeferMutationCacheUpdates()) {
331
+ this.invalidateCachedIndexes();
332
+ return;
333
+ }
334
+ for (let t of this.indexedFields) {
335
+ let n = this.cache.get(t);
336
+ if (n) {
337
+ if (!this.shouldMaintainIncrementally(n)) {
338
+ this.cache.delete(t);
339
+ continue;
340
+ }
341
+ if (!n.hasDuplicateValues) {
342
+ this.updateUniqueCachedIndexForRemovedItems(n, e), n.version = this.state.getMutationVersion();
343
+ continue;
344
+ }
345
+ this.cache.delete(t);
346
+ }
347
+ }
348
+ }
349
+ updateCachedIndexForRemovedItem(e, t, n) {
350
+ let r = this.cache.get(e);
351
+ if (!r) return;
352
+ if (!r.hasDuplicateValues) {
353
+ this.updateUniqueCachedIndexForRemovedItem(r, t, n), r.version = this.state.getMutationVersion();
354
+ return;
355
+ }
356
+ let i = [];
357
+ for (let e = 0; e < r.indexes.length; e++) {
358
+ let a = r.indexes[e];
359
+ a === t || a === n || i.push(a);
360
+ }
361
+ if (n !== null && n !== t) {
362
+ let n = 0, r = i.length;
363
+ for (; n < r;) {
364
+ let a = n + r >> 1;
365
+ this.compareIndexesByField(e, i[a], t) <= 0 ? n = a + 1 : r = a;
366
+ }
367
+ i.splice(n, 0, t);
368
+ }
369
+ let a = Uint32Array.from(i), o = new Uint32Array(this.dataset.length);
370
+ for (let e = 0; e < a.length; e++) {
371
+ let t = a[e];
372
+ o[t] = e;
373
+ }
374
+ r.indexes = a, r.reverseIndex = o, r.ascItems = r.ascItems ? this.materializeItemsFromIndexes(this.dataset, a, "asc") : null, r.descItems = null, r.hasDuplicateValues = r.hasDuplicateValues ? this.hasDuplicateValuesForIndexes(this.dataset, a, e) : !1, r.version = this.state.getMutationVersion();
375
+ }
376
+ updateUniqueCachedIndexForRemovedItem(e, t, n) {
377
+ let r = e.indexes.length - 1, i = new Uint32Array(r), a = new Uint32Array(this.dataset.length), o = e.ascItems === null ? null : Array(r), s = 0;
378
+ for (let r = 0; r < e.indexes.length; r++) {
379
+ let c = e.indexes[r];
380
+ if (c === t) continue;
381
+ let l = n !== null && c === n ? t : c;
382
+ i[s] = l, a[l] = s, o !== null && (o[s] = this.dataset[l]), s += 1;
383
+ }
384
+ e.indexes = i, e.reverseIndex = a, e.ascItems = o, e.descItems = null;
385
+ }
386
+ updateUniqueCachedIndexForRemovedItems(e, t) {
387
+ let n = e.indexes.length, r = new Uint32Array(n), i = new Int32Array(n);
388
+ for (let e = 0; e < n; e++) r[e] = e, i[e] = -1;
389
+ let a = n;
390
+ for (let e = 0; e < t.length; e++) {
391
+ let n = t[e];
392
+ n.movedFromIndex !== null && (r[n.removedIndex] = r[n.movedFromIndex]), --a;
393
+ }
394
+ let o = new Uint32Array(a), s = new Uint32Array(a), c = e.ascItems === null ? null : Array(a);
395
+ for (let e = 0; e < a; e++) i[r[e]] = e;
396
+ let l = 0;
397
+ for (let t = 0; t < e.indexes.length; t++) {
398
+ let n = i[e.indexes[t]];
399
+ n !== -1 && (o[l] = n, s[n] = l, c !== null && (c[l] = this.dataset[n]), l += 1);
400
+ }
401
+ e.indexes = o, e.reverseIndex = s, e.ascItems = c, e.descItems = null;
402
+ }
403
+ buildComparator(e) {
404
+ let t = e.map(({ field: e }) => e), n = e.map(({ direction: e }) => e === "asc" ? 1 : -1), r = t.length;
405
+ return (e, i) => {
406
+ for (let a = 0; a < r; a++) {
407
+ let r = t[a], o = e[r], s = i[r];
408
+ if (o < s) return -n[a];
409
+ if (o > s) return n[a];
410
+ }
411
+ return 0;
412
+ };
413
+ }
414
+ };
415
+ //#endregion
416
+ export { s as SortEngine };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devisfuture/mega-collection",
3
- "version": "2.4.3",
3
+ "version": "2.4.5",
4
4
  "description": "High-performance search, filter & sort engine for 100K+ item collections in JavaScript/TypeScript",
5
5
  "exports": {
6
6
  ".": {
@@ -42,13 +42,24 @@
42
42
  }
43
43
  },
44
44
  "files": [
45
- "dist"
45
+ "dist/index.mjs",
46
+ "dist/index.d.mts",
47
+ "dist/chunk-*.mjs",
48
+ "dist/search/index.mjs",
49
+ "dist/search/index.d.mts",
50
+ "dist/filter/index.mjs",
51
+ "dist/filter/index.d.mts",
52
+ "dist/sort/index.mjs",
53
+ "dist/sort/index.d.mts",
54
+ "dist/merge/index.mjs",
55
+ "dist/merge/index.d.mts"
46
56
  ],
47
57
  "sideEffects": false,
48
58
  "scripts": {
49
- "build": "tsup",
50
- "build:watch": "tsup --watch",
51
- "dev": "tsup --watch",
59
+ "build:types": "tsc --emitDeclarationOnly && node ./scripts/rename-dts-to-dmts.js",
60
+ "build": "vite build && npm run build:types",
61
+ "build:watch": "vite build --watch",
62
+ "dev": "vite build --watch",
52
63
  "test": "vitest run",
53
64
  "test:watch": "vitest",
54
65
  "sort-bench": "npx tsx ./benchmarks/sorter.bench.ts",
@@ -95,10 +106,10 @@
95
106
  },
96
107
  "devDependencies": {
97
108
  "@types/node": "^25.5.0",
98
- "@vitest/coverage-v8": "^2.1.9",
99
- "tsup": "^8.0.0",
109
+ "@vitest/coverage-v8": "^4.1.0",
100
110
  "typescript": "^5.3.0",
101
- "vitest": "^2.1.8"
111
+ "vite": "^8.0.0",
112
+ "vitest": "^4.1.0"
102
113
  },
103
114
  "license": "MIT"
104
115
  }
@@ -1,44 +0,0 @@
1
- import { C as CollectionItem, S as StateOptions, a as StateListener, b as StatePreviousResult, c as StateRegistryFactory, U as UpdateDescriptor, I as IndexableKey } from './types-DONld7xY.mjs';
2
-
3
- declare class State<T extends CollectionItem> {
4
- private originData;
5
- private filterByPreviousResult;
6
- private itemIndexLookup;
7
- private mutationVersion;
8
- private namespaceSequence;
9
- private previousResultState;
10
- private readonly indexMaps;
11
- private readonly scopedRegistry;
12
- private readonly listeners;
13
- constructor(data?: T[], options?: StateOptions);
14
- subscribe(listener: StateListener<T>): () => void;
15
- getOriginData(): T[];
16
- getItemIndex(item: T): number | undefined;
17
- getMutationVersion(): number;
18
- isFilterByPreviousResultEnabled(): boolean;
19
- setFilterByPreviousResult(enabled: boolean): void;
20
- getPreviousResult(): T[] | null;
21
- getPreviousResultState(): StatePreviousResult<T> | null;
22
- setPreviousResult(result: T[], sourceData: T[]): void;
23
- clearPreviousResult(): void;
24
- createNamespace(prefix?: string): string;
25
- getScopedValue<TValue>(namespace: string, key: string): TValue | undefined;
26
- getOrCreateScopedValue<TValue>(namespace: string, key: string, createValue: StateRegistryFactory<TValue>): TValue;
27
- setScopedValue<TValue>(namespace: string, key: string, value: TValue): TValue;
28
- deleteScopedValue(namespace: string, key: string): void;
29
- clearScope(namespace: string): void;
30
- data(data: T[]): void;
31
- add(items: T[]): void;
32
- update(descriptor: UpdateDescriptor<T>): void;
33
- clearData(): void;
34
- removeByFieldValue(field: IndexableKey<T> & string, value: any): void;
35
- removeByFieldValues(field: IndexableKey<T> & string, values: any[]): void;
36
- private emit;
37
- private getOrCreateScope;
38
- private bumpMutationVersion;
39
- private getOrCreateIndexMap;
40
- private rebuildIndexMap;
41
- private rebuildItemIndexLookup;
42
- }
43
-
44
- export { State as S };
@@ -1 +0,0 @@
1
- import {a,b}from'./chunk-MB56OSRQ.mjs';function p(o){return {value:o,enumerable:false,configurable:true,writable:true}}var f=class{constructor(e){this.callbacks=e;}create(e){let t=e;return Object.defineProperties(t,{search:p((i,r)=>r===void 0?this.callbacks.search(i):this.callbacks.search(i,r)),sort:p((i,r,n)=>r===void 0?this.callbacks.sort(e,i,n):this.callbacks.sort(i,r,n)),filter:p((i,r)=>r===void 0?this.callbacks.filter(e,i):this.callbacks.filter(i,r)),add:p(i=>this.callbacks.add(i)),update:p(i=>this.callbacks.update(i)),clearIndexes:p(i=>(this.callbacks.clearIndexes(i),this.create(e))),clearData:p(i=>(this.callbacks.clearData(i),this.create(e))),data:p(i=>this.callbacks.data(i)),getOriginData:p(()=>this.callbacks.getOriginData())}),t}};function T(o){return typeof o=="object"&&o!==null}function M(o,e){return T(o)&&typeof o[e]=="function"}function F(o){return M(o,"search")&&M(o,"getOriginData")}function m(o){return M(o,"sort")&&M(o,"getOriginData")}function D(o){return M(o,"rawFilter")&&M(o,"getOriginData")}var I=o=>{let{prototype:e}=o;return D(e)?"filter":m(e)?"sort":F(e)?"search":null},x=(o,e,t,i)=>{let r=new o({data:e,state:t,...i});return D(r)?{moduleName:"filter",executeFilter:(n,s)=>s===void 0?r.rawFilter(n):r.rawFilter(n,s),clearIndexes:()=>r.clearIndexes()}:m(r)?{moduleName:"sort",executeSort:(n,s,l)=>s===void 0?r.sort(n):r.sort(n,s,l),clearIndexes:()=>r.clearIndexes()}:F(r)?{moduleName:"search",executeSearch:(n,s)=>s===void 0?r.search(n):r.search(n,s),clearIndexes:()=>r.clearIndexes()}:null};var y="deferSortMutationCacheUpdates",P="deferSearchMutationIndexUpdates",R="deferFilterMutationIndexUpdates",w={search:"TextSearchEngine",sort:"SortEngine",filter:"FilterEngine"};var d=class o extends Error{constructor(e){super(e),this.name="MergeEnginesError";}static unavailableEngine(e){let t=w[e];return new o(`MergeEngines: ${t} is not available.`)}static unavailableGetOriginData(){return new o("MergeEngines: getOriginData is not available.")}static invalidFilterByPreviousResultOption(){return new o('MergeEngines: "filter.filterByPreviousResult" is not supported. Configure "filterByPreviousResult" on the MergeEngines root options.')}};var C=class{constructor(e){this.previousSearchState=null;this.previousFilterState=null;this.previousSortState=null;let{imports:t,data:i,filterByPreviousResult:r=false,...n}=e;this.validateFilterByPreviousResultOptions(n.filter),this.state=new a(i,{filterByPreviousResult:r});let s=new Set(t),l=null,u=null,c=null;for(let a of s){let h=I(a);if(!h)continue;let v=this.getModuleInitOptions(h,a.name,n),g=x(a,i,this.state,v);g&&(g.moduleName==="search"&&!l&&(l=g),g.moduleName==="sort"&&!u&&(u=g),g.moduleName==="filter"&&!c&&(c=g));}this.searchModule=l,this.sortModule=u,this.filterModule=c,this.sortModule&&this.state.setScopedValue(b,y,true),this.searchModule&&this.state.setScopedValue(b,P,true),this.filterModule&&this.state.setScopedValue(b,R,true),this.state.subscribe(a=>this.handleStateMutation(a)),this.chainBuilder=new f({search:(a,h)=>h===void 0?this.search(a):this.search(a,h),sort:(a,h,v)=>this.sort(a,h,v),filter:(a,h)=>this.filter(a,h),getOriginData:()=>this.getOriginData(),add:a=>this.add(a),update:a=>this.update(a),data:a=>this.data(a),clearIndexes:a=>this.clearIndexes(a),clearData:a=>this.clearData(a)});}getAdapter(e){return e==="search"?this.searchModule:e==="sort"?this.sortModule:this.filterModule}getModuleInitOptions(e,t,i){let r={};for(let n of [e,t]){let s=i[n];T(s)&&Object.assign(r,s);}return r}validateFilterByPreviousResultOptions(e){if(T(e)&&Object.prototype.hasOwnProperty.call(e,"filterByPreviousResult"))throw d.invalidFilterByPreviousResultOption()}isPreviousResultEnabled(){return this.state.isFilterByPreviousResultEnabled()}getPreviousResultInput(){return this.isPreviousResultEnabled()?this.state.getPreviousResult():null}trackPreviousResult(e,t){return this.isPreviousResultEnabled()&&this.state.setPreviousResult(e,t),e}clearOperationState(e){(!e||e==="search")&&(this.previousSearchState=null),(!e||e==="filter")&&(this.previousFilterState=null),(!e||e==="sort")&&(this.previousSortState=null);}createSearchCacheKey(e,t){return JSON.stringify([e,t??null])}createSortCacheKey(e,t){return JSON.stringify({descriptors:e,inPlace:t??false})}createFilterCacheKey(e){return JSON.stringify(e)}handleStateMutation(e){switch(e.type){case "add":this.queueSearchCacheMutation(e),this.queueFilterCacheMutation(e),this.queueSortCacheMutation(e);return;case "update":this.queueSearchCacheMutation(e),this.queueFilterCacheMutation(e),this.queueSortCacheMutation(e);return;case "remove":this.previousSearchState=null,this.previousFilterState=null,this.queueSortCacheMutation(e);return;case "removeMany":this.previousSearchState=null,this.previousFilterState=null,this.queueSortCacheMutation(e);return;case "data":case "clearData":this.previousSearchState=null,this.previousFilterState=null,this.previousSortState=null;return}}queueSearchCacheMutation(e){let t=this.previousSearchState;if(t!==null){if(!this.canPatchStoredDatasetSearch(t)){this.previousSearchState=null;return}this.previousSearchState={...t,version:this.state.getMutationVersion(),pendingMutations:t.pendingMutations.concat(e)};}}queueFilterCacheMutation(e){let t=this.previousFilterState;if(t!==null){if(!this.canPatchStoredDatasetFilter(t)){this.previousFilterState=null;return}this.previousFilterState={...t,version:this.state.getMutationVersion(),pendingMutations:t.pendingMutations.concat(e)};}}queueSortCacheMutation(e){let t=this.previousSortState;if(t!==null){if(!this.canPatchStoredDatasetSort(t)){this.previousSortState=null;return}this.previousSortState={...t,version:this.state.getMutationVersion(),pendingMutations:t.pendingMutations.concat(e)};}}resolvePendingSortCache(e){if(e.pendingMutations.length===0)return e;let t={...e,pendingMutations:[]};for(let i=0;i<e.pendingMutations.length;i++)if(t=this.applySortCacheMutation(t,e.pendingMutations[i]),t===null)return null;return t}resolvePendingSearchCache(e){if(e.pendingMutations.length===0)return e;let t={...e,pendingMutations:[]};for(let i=0;i<e.pendingMutations.length;i++)if(t=this.applySearchCacheMutation(t,e.pendingMutations[i]),t===null)return null;return t}resolvePendingFilterCache(e){if(e.pendingMutations.length===0)return e;let t={...e,pendingMutations:[]};for(let i=0;i<e.pendingMutations.length;i++)if(t=this.applyFilterCacheMutation(t,e.pendingMutations[i]),t===null)return null;return t}applySortCacheMutation(e,t){switch(t.type){case "add":return this.patchSortCacheForAddedItems(e,t.items);case "update":return this.patchSortCacheForUpdatedItem(e,t.previousItem,t.nextItem);case "remove":return this.patchSortCacheForRemovedItems(e,[t.removedItem]);case "removeMany":return this.patchSortCacheForRemovedItems(e,t.entries.map(i=>i.removedItem));case "data":case "clearData":return null}}applySearchCacheMutation(e,t){switch(t.type){case "add":return this.patchSearchCacheForAddedItems(e,t.items);case "update":return this.patchSearchCacheForUpdatedItem(e,t.previousItem,t.nextItem);case "remove":case "removeMany":case "data":case "clearData":return null}}applyFilterCacheMutation(e,t){switch(t.type){case "add":return this.patchFilterCacheForAddedItems(e,t.items);case "update":return this.patchFilterCacheForUpdatedItem(e,t.previousItem,t.nextItem);case "remove":case "removeMany":case "data":case "clearData":return null}}canPatchStoredDatasetSearch(e){return e.originData===this.state.getOriginData()&&e.field!==null}canPatchStoredDatasetFilter(e){if(e.sourceData!==this.state.getOriginData())return false;for(let t=0;t<e.criteria.length;t++)if(!this.isPatchableFilterCriterion(e.criteria[t]))return false;return true}canPatchStoredDatasetSort(e){return e.sourceData===this.state.getOriginData()}compareItemsByDescriptors(e,t,i){for(let r=0;r<i.length;r++){let{field:n,direction:s}=i[r],l=e[n],u=t[n];if(l<u)return s==="asc"?-1:1;if(l>u)return s==="asc"?1:-1}return (this.state.getItemIndex(e)??-1)-(this.state.getItemIndex(t)??-1)}findSortInsertPosition(e,t,i){let r=0,n=e.length;for(;r<n;){let s=r+n>>1;this.compareItemsByDescriptors(e[s],t,i)<=0?r=s+1:n=s;}return r}findDatasetInsertPosition(e,t){let i=this.state.getItemIndex(t)??Number.MAX_SAFE_INTEGER;for(let r=0;r<e.length;r++)if((this.state.getItemIndex(e[r])??Number.MAX_SAFE_INTEGER)>i)return r;return e.length}doesItemMatchSearchCache(e,t){if(e.field===null||e.lowerQuery.length===0)return false;let i=t[e.field];return typeof i=="string"&&i.toLowerCase().includes(e.lowerQuery)}patchSearchCacheForAddedItems(e,t){if(!this.canPatchStoredDatasetSearch(e))return null;let i=e.result.slice();for(let r=0;r<t.length;r++){let n=t[r];this.doesItemMatchSearchCache(e,n)&&i.push(n);}return {...e,result:i,pendingMutations:[],version:this.state.getMutationVersion()}}patchSearchCacheForUpdatedItem(e,t,i){if(!this.canPatchStoredDatasetSearch(e))return null;let r=e.result.slice(),n=r.indexOf(t),s=this.doesItemMatchSearchCache(e,i);if(n!==-1)s?r[n]=i:r.splice(n,1);else if(s){let l=this.findDatasetInsertPosition(r,i);r.splice(l,0,i);}return {...e,result:r,pendingMutations:[],version:this.state.getMutationVersion()}}isPatchableFilterCriterion(e){return !String(e.field).includes(".")}doesItemMatchFilterCache(e,t){for(let i=0;i<e.criteria.length;i++){let r=e.criteria[i];if(!this.isPatchableFilterCriterion(r))return false;let n=t[r.field];if(r.values!==void 0&&r.values.length>0&&!r.values.includes(n)||r.exclude!==void 0&&r.exclude.length>0&&r.exclude.includes(n))return false}return true}patchFilterCacheForAddedItems(e,t){if(!this.canPatchStoredDatasetFilter(e))return null;let i=e.result.slice();for(let r=0;r<t.length;r++){let n=t[r];this.doesItemMatchFilterCache(e,n)&&i.push(n);}return {...e,result:i,pendingMutations:[],version:this.state.getMutationVersion()}}patchFilterCacheForUpdatedItem(e,t,i){if(!this.canPatchStoredDatasetFilter(e))return null;let r=e.result.slice(),n=r.indexOf(t),s=this.doesItemMatchFilterCache(e,i);if(n!==-1)s?r[n]=i:r.splice(n,1);else if(s){let l=this.findDatasetInsertPosition(r,i);r.splice(l,0,i);}return {...e,result:r,pendingMutations:[],version:this.state.getMutationVersion()}}patchSortCacheForAddedItems(e,t){if(!this.canPatchStoredDatasetSort(e))return null;let i=e.result.slice();for(let r=0;r<t.length;r++){let n=t[r],s=this.findSortInsertPosition(i,n,e.descriptors);i.splice(s,0,n);}return {...e,result:i,pendingMutations:[],version:this.state.getMutationVersion()}}patchSortCacheForUpdatedItem(e,t,i){if(!this.canPatchStoredDatasetSort(e))return null;let r=e.result.slice(),n=r.indexOf(t);if(n===-1)return e.result.indexOf(i)!==-1?{...e,pendingMutations:[],version:this.state.getMutationVersion()}:null;if(!e.descriptors.some(({field:u})=>t[u]!==i[u]))return r[n]=i,{...e,result:r,pendingMutations:[],version:this.state.getMutationVersion()};r.splice(n,1);let l=this.findSortInsertPosition(r,i,e.descriptors);return r.splice(l,0,i),{...e,result:r,pendingMutations:[],version:this.state.getMutationVersion()}}patchSortCacheForRemovedItems(e,t){if(!this.canPatchStoredDatasetSort(e))return null;let i=new Set(t);return {...e,result:Array.prototype.filter.call(e.result,r=>!i.has(r)),pendingMutations:[],version:this.state.getMutationVersion()}}search(e,t){if(!this.searchModule)throw d.unavailableEngine("search");let i=this.state.getOriginData(),r=this.state.getMutationVersion(),n=this.createSearchCacheKey(e,t),s=this.previousSearchState;if(s?.originData===i&&s.key===n&&s.version===r){let u=this.resolvePendingSearchCache(s);if(u!==null)return this.previousSearchState=u,this.withChain(this.trackPreviousResult(u.result,i));this.previousSearchState=null;}let l=t===void 0?this.searchModule.executeSearch(e):this.searchModule.executeSearch(e,t);return this.previousSearchState={key:n,originData:i,result:l,version:r,field:t===void 0?null:e,lowerQuery:(t??e).trim().toLowerCase(),pendingMutations:[]},this.withChain(this.trackPreviousResult(l,i))}sort(e,t,i){if(!this.sortModule)throw d.unavailableEngine("sort");let r,n;if(t===void 0?(n=e,r=this.getPreviousResultInput()??this.state.getOriginData()):(r=e,n=t),!i){let s=this.state.getMutationVersion(),l=this.createSortCacheKey(n,i),u=this.previousSortState;if(u?.sourceData===r&&u.key===l&&u.version===s){let a=this.resolvePendingSortCache(u);if(a!==null)return this.previousSortState=a,this.withChain(this.trackPreviousResult(a.result,r));this.previousSortState=null;}let c=t===void 0&&r===this.state.getOriginData()?this.sortModule.executeSort(n):this.sortModule.executeSort(r,n,i);return this.previousSortState={key:l,sourceData:r,result:c,version:s,descriptors:n,pendingMutations:[]},this.withChain(this.trackPreviousResult(c,r))}return this.withChain(this.trackPreviousResult(this.sortModule.executeSort(r,n,i),r))}filter(e,t){if(!this.filterModule)throw d.unavailableEngine("filter");if(t===void 0){let r=this.getPreviousResultInput(),n=r??this.state.getOriginData(),s=e,l=this.state.getMutationVersion(),u=this.createFilterCacheKey(s),c=this.previousFilterState;if(c?.sourceData===n&&c.key===u&&c.version===l){let h=this.resolvePendingFilterCache(c);if(h!==null)return this.previousFilterState=h,this.withChain(this.trackPreviousResult(h.result,n));this.previousFilterState=null;}let a=r===null?this.filterModule.executeFilter(s):this.filterModule.executeFilter(r,s);return this.previousFilterState={key:u,sourceData:n,result:a,version:l,criteria:s,pendingMutations:[]},this.withChain(this.trackPreviousResult(a,n))}let i=e;return this.withChain(this.trackPreviousResult(this.filterModule.executeFilter(i,t),i))}withChain(e){return this.chainBuilder.create(e)}getOriginData(){if(this.searchModule||this.sortModule||this.filterModule)return this.state.getOriginData();throw d.unavailableGetOriginData()}add(e){return e.length===0?this:(this.state.add(e),this)}update(e){return this.state.update(e),this}clearIndexes(e){let t=this.getAdapter(e);if(t)return t.clearIndexes(),this.clearOperationState(e),this;throw d.unavailableEngine(e)}data(e){return this.state.data(e),this}clearData(e){if(this.getAdapter(e))return this.state.clearData(),this;throw d.unavailableEngine(e)}};export{C as a};
@@ -1 +0,0 @@
1
- var g=class{constructor(e=[],t={}){this.itemIndexLookup=new WeakMap;this.mutationVersion=0;this.namespaceSequence=0;this.previousResultState=null;this.indexMaps=new Map;this.scopedRegistry=new Map;this.listeners=new Set;this.originData=e,this.filterByPreviousResult=t.filterByPreviousResult??false,this.rebuildItemIndexLookup();}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}getOriginData(){return this.originData}getItemIndex(e){return this.itemIndexLookup.get(e)}getMutationVersion(){return this.mutationVersion}isFilterByPreviousResultEnabled(){return this.filterByPreviousResult}setFilterByPreviousResult(e){this.filterByPreviousResult=e,e||this.clearPreviousResult();}getPreviousResult(){return this.getPreviousResultState()?.result??null}getPreviousResultState(){return this.previousResultState===null||this.previousResultState.version!==this.mutationVersion?null:this.previousResultState}setPreviousResult(e,t){this.previousResultState={result:e,sourceData:t,version:this.mutationVersion};}clearPreviousResult(){this.previousResultState=null;}createNamespace(e="scope"){return this.namespaceSequence+=1,`${e}:${this.namespaceSequence}`}getScopedValue(e,t){return this.scopedRegistry.get(e)?.get(t)}getOrCreateScopedValue(e,t,i){let n=this.getScopedValue(e,t);if(n!==void 0)return n;let o=this.getOrCreateScope(e),r=i();return o.set(t,r),r}setScopedValue(e,t,i){return this.getOrCreateScope(e).set(t,i),i}deleteScopedValue(e,t){let i=this.scopedRegistry.get(e);i&&(i.delete(t),i.size===0&&this.scopedRegistry.delete(e));}clearScope(e){this.scopedRegistry.delete(e);}data(e){this.originData=e,this.bumpMutationVersion(),this.rebuildItemIndexLookup();for(let t of this.indexMaps.keys())this.rebuildIndexMap(t);this.emit({type:"data",data:e});}add(e){if(e.length===0)return;let t=this.originData.length;for(let i=0;i<e.length;i++)this.originData.push(e[i]),this.itemIndexLookup.set(e[i],t+i);this.bumpMutationVersion();for(let[i,n]of this.indexMaps)for(let o=0;o<e.length;o++)n.set(e[o][i],t+o);this.emit({type:"add",items:e,startIndex:t});}update(e){let{field:t,data:i}=e,n=i[t];if(n==null)return;let r=this.getOrCreateIndexMap(t).get(n);if(r===void 0)return;let s=this.originData[r];this.originData[r]=i,this.itemIndexLookup.delete(s),this.itemIndexLookup.set(i,r),this.bumpMutationVersion();for(let[d,u]of this.indexMaps){let a=s[d],l=i[d];a!==l&&(u.get(a)===r&&u.delete(a),u.set(l,r));}this.emit({type:"update",field:t,index:r,previousItem:s,nextItem:i});}clearData(){let e=[];this.originData=e,this.itemIndexLookup=new WeakMap,this.bumpMutationVersion();for(let t of this.indexMaps.values())t.clear();this.emit({type:"clearData",data:e});}removeByFieldValue(e,t){let n=this.getOrCreateIndexMap(e).get(t);if(n===void 0)return;let o=this.originData.length-1,r=this.originData[n],s=n===o?null:this.originData[o];n!==o&&s&&(this.originData[n]=s,this.itemIndexLookup.set(s,n)),this.originData.pop(),this.itemIndexLookup.delete(r),this.bumpMutationVersion();for(let[d,u]of this.indexMaps){let a=r[d];u.get(a)===n&&u.delete(a),s&&u.set(s[d],n);}this.emit({type:"remove",field:e,value:t,removedItem:r,removedIndex:n,movedItem:s,movedFromIndex:s?o:null});}removeByFieldValues(e,t){if(t.length===0)return;let i=this.getOrCreateIndexMap(e),n=[];for(let o=0;o<t.length;o++){let r=t[o],s=i.get(r);if(s===void 0)continue;let d=this.originData.length-1,u=this.originData[s],a=s===d?null:this.originData[d];s!==d&&a&&(this.originData[s]=a,this.itemIndexLookup.set(a,s)),this.originData.pop(),this.itemIndexLookup.delete(u);for(let[l,p]of this.indexMaps){let h=u[l];p.get(h)===s&&p.delete(h),a&&p.set(a[l],s);}n.push({value:r,removedItem:u,removedIndex:s,movedItem:a,movedFromIndex:a?d:null});}n.length!==0&&(this.bumpMutationVersion(),this.emit({type:"removeMany",field:e,entries:n}));}emit(e){for(let t of this.listeners)t(e);}getOrCreateScope(e){let t=this.scopedRegistry.get(e);if(t)return t;let i=new Map;return this.scopedRegistry.set(e,i),i}bumpMutationVersion(){this.mutationVersion+=1,this.clearPreviousResult();}getOrCreateIndexMap(e){let t=this.indexMaps.get(e);return t||this.rebuildIndexMap(e)}rebuildIndexMap(e){let t=new Map;for(let i=0;i<this.originData.length;i++)t.set(this.originData[i][e],i);return this.indexMaps.set(e,t),t}rebuildItemIndexLookup(){this.itemIndexLookup=new WeakMap;for(let e=0;e<this.originData.length;e++)this.itemIndexLookup.set(this.originData[e],e);}};var m="__merge__";export{g as a,m as b};