An open source alternative to Tableau. Embeddable visual analytic
TypeScript bidatadata-analysisdata-miningdata-visualizationedak6skanarieslow-codepivot-tablereacttableautableau-alternativetypescriptvegavega-litevisualization
fix: use sparse array (#453)
islxyqwe7623bb4a3b1c
diff --git a/packages/graphic-walker/package.json b/packages/graphic-walker/package.jsonindex eec232cd..cb5cfbaf 100644--- a/packages/graphic-walker/package.json+++ b/packages/graphic-walker/package.json@@ -87,6 +87,7 @@"i18next": "^21.9.1","i18next-browser-languagedetector": "^6.1.5","immer": "^9.0.15",+ "immutable": "^5.1.1","jest": "^29.6.2","leaflet": "^1.9.4","lodash-es": "^4.17.15",diff --git a/packages/graphic-walker/src/fields/filterField/array.test.ts b/packages/graphic-walker/src/fields/filterField/array.test.tsnew file mode 100644index 00000000..32a20bcf--- /dev/null+++ b/packages/graphic-walker/src/fields/filterField/array.test.ts@@ -0,0 +1,53 @@+import { SparseArray } from './array';++describe('SparseArray', () => {+ it('should create an empty SparseArray', () => {+ const arr = SparseArray.create<number>();+ expect(arr.get(0)).toBeNull();+ });++ it('should set and get values', () => {+ let arr = SparseArray.create<string>();+ arr = arr.set(10, 'foo');+ arr = arr.set(1000000, 'bar');+ expect(arr.get(10)).toBe('foo');+ expect(arr.get(1000000)).toBe('bar');+ expect(arr.get(5)).toBeNull();+ });++ it('should slice with unset indices as null', () => {+ let arr = SparseArray.create<number>();+ arr = arr.set(2, 42);+ arr = arr.set(4, 99);+ expect(arr.slice(0, 6)).toEqual([null, null, 42, null, 99, null]);+ });++ it('should putIn a range of items', () => {+ let arr = SparseArray.create<number>();+ arr = arr.putIn(5, [1, 2, 3]);+ expect(arr.get(5)).toBe(1);+ expect(arr.get(6)).toBe(2);+ expect(arr.get(7)).toBe(3);+ expect(arr.get(8)).toBeNull();+ expect(arr.slice(4, 9)).toEqual([null, 1, 2, 3, null]);+ });++ it('should handle large indices efficiently', () => {+ let arr = SparseArray.create<string>();+ arr = arr.set(100_000_000, 'big');+ expect(arr.get(100_000_000)).toBe('big');+ expect(arr.get(0)).toBeNull();+ });++ it('should be immutable', () => {+ const arr1 = SparseArray.create<number>();+ const arr2 = arr1.set(5, 42);++ expect(arr1.get(5)).toBeNull();+ expect(arr2.get(5)).toBe(42);++ const arr3 = arr2.putIn(10, [1, 2, 3]);+ expect(arr2.get(10)).toBeNull();+ expect(arr3.get(10)).toBe(1);+ });+});diff --git a/packages/graphic-walker/src/fields/filterField/array.ts b/packages/graphic-walker/src/fields/filterField/array.tsnew file mode 100644index 00000000..5cf4a80a--- /dev/null+++ b/packages/graphic-walker/src/fields/filterField/array.ts@@ -0,0 +1,38 @@+import { OrderedMap } from 'immutable';++export class SparseArray<T> {+ private tree: OrderedMap<number, T>;++ private constructor(tree?: OrderedMap<number, T>) {+ this.tree = tree || OrderedMap<number, T>();+ }++ static create<T>() {+ return new SparseArray<T>();+ }++ get(index: number): T | null {+ return this.tree.has(index) ? this.tree.get(index)! : null;+ }++ set(index: number, item: T): SparseArray<T> {+ const newTree = this.tree.set(index, item);+ return new SparseArray<T>(newTree);+ }++ slice(start: number, end: number): (T | null)[] {+ const result: (T | null)[] = [];+ for (let i = start; i < end; i++) {+ result.push(this.get(i));+ }+ return result;+ }++ putIn(start: number, items: T[]): SparseArray<T> {+ let newTree = this.tree;+ for (let i = 0; i < items.length; i++) {+ newTree = newTree.set(start + i, items[i]);+ }+ return new SparseArray<T>(newTree);+ }+}diff --git a/packages/graphic-walker/src/fields/filterField/simple.tsx b/packages/graphic-walker/src/fields/filterField/simple.tsxindex 04eaa24f..d64f2f43 100644--- a/packages/graphic-walker/src/fields/filterField/simple.tsx+++ b/packages/graphic-walker/src/fields/filterField/simple.tsx@@ -15,6 +15,7 @@ import { createStreamedValueHook, useDebounceValueBind } from '../../hooks';import { GLOBAL_CONFIG } from '../../config';import { debounce } from 'lodash-es';import { Input } from '@/components/ui/input';+import { SparseArray } from './array';const sortConfig = {key: 'value',@@ -242,7 +243,7 @@ function VirtualList({}: {field: IFilterField;distinctTotal?: number;- data: ({ value: string | number; count: number } | null)[];+ data: SparseArray<{ value: string | number; count: number }>;handleSelect: (value: string | number, checked: boolean, itemNum: number) => void;loadData: (index: number) => void;displayOffset?: number;@@ -275,7 +276,7 @@ function VirtualList({>{rowVirtualizer.getVirtualItems().map((vItem) => {const idx = vItem.index;- const item = data?.[idx];+ const item = data?.get(idx);if (!item) {return (<divdiff --git a/packages/graphic-walker/src/fields/filterField/tabs.tsx b/packages/graphic-walker/src/fields/filterField/tabs.tsxindex 77a5cbbb..f8dee7a1 100644--- a/packages/graphic-walker/src/fields/filterField/tabs.tsx+++ b/packages/graphic-walker/src/fields/filterField/tabs.tsx@@ -21,6 +21,7 @@ import { Input } from '@/components/ui/input';import { Skeleton } from '@/components/ui/skeleton';import { Checkbox } from '@/components/ui/checkbox';import Tooltip from '@/components/tooltip';+import { SparseArray } from './array';export type RuleFormProps = {allFields: IMutField[];@@ -174,30 +175,12 @@ export const useFieldStats = (};const PAGE_SIZE = 20;-const emptyArray = [];+const emptyArray = SparseArray.create<RowCount>();type RowCount = {value: string | number;count: number;};-function putDataInArray<T>(arr: T[], dataToPut: T[], fromIndex: number, emptyFill: T) {- const putin = (array: T[]) =>- array.map((x, i) => {- const targetIndex = i - fromIndex;- if (targetIndex >= 0 && targetIndex < dataToPut.length) {- return dataToPut[targetIndex];- }- return x;- });-- const requiredLength = dataToPut.length + fromIndex;- if (arr.length >= requiredLength) {- return putin(arr);- }- const filledArray = arr.concat(new Array<T>(requiredLength - arr.length).fill(emptyFill));- return putin(filledArray);-}-export const useVisualCount = (field: IFilterField,sortBy: 'value' | 'value_dsc' | 'count' | 'count_dsc' | 'none',@@ -234,9 +217,9 @@ export const useVisualCount = (}, [metaData]);// unfetched RowCount will be null- const [loadedPageData, setLoadedPageDataRaw] = useState<(RowCount | null)[]>(emptyArray);+ const [loadedPageData, setLoadedPageDataRaw] = useState<SparseArray<RowCount>>(emptyArray);const loadedRef = useRef(loadedPageData);- const setLoadedPageData = useCallback((data: (RowCount | null)[] | ((prev: (RowCount | null)[]) => (RowCount | null)[])) => {+ const setLoadedPageData = useCallback((data: SparseArray<RowCount> | ((prev: SparseArray<RowCount>) => SparseArray<RowCount>)) => {if (typeof data === 'function') {loadedRef.current = data(loadedRef.current);} else {@@ -250,7 +233,7 @@ export const useVisualCount = (const loadData = useCallback((index: number) => {const page = Math.floor(index / PAGE_SIZE);- if (loadedRef.current.length <= index || loadedRef.current[index] === null) {+ if (loadedRef.current.get(index) === null) {if (loadingRef.current[page] === undefined) {const promise = fieldStat(computation,@@ -272,7 +255,9 @@ export const useVisualCount = (// check that the list is not clearedif (loadingRef.current[page] === promise) {const { values } = stats;- setLoadedPageData((data) => putDataInArray(data, values, page * PAGE_SIZE, null));+ setLoadedPageData((data) => {+ return data.putIn(page * PAGE_SIZE, values);+ });}});}@@ -284,15 +269,15 @@ export const useVisualCount = (// clear data when field or sort changesuseEffect(() => {loadingRef.current = {};- setLoadedPageData(emptyArray);+ setLoadedPageData(SparseArray.create<RowCount>());loadData(0);}, [loadData]);const loadingPageData = loadedPageData === emptyArray || !currentMeta;const data = useMemo(() => {- if (!currentMeta?.valuesMeta.distinctTotal) return [];- return loadedPageData.concat(new Array<null>(Math.max(currentMeta.valuesMeta.distinctTotal - loadedPageData.length, 0)).fill(null));+ if (!currentMeta?.valuesMeta.distinctTotal) return emptyArray;+ return loadedPageData;}, [loadedPageData, currentMeta?.valuesMeta.distinctTotal]);const currentCount =@@ -620,7 +605,7 @@ export const FilterOneOfRule: React.FC<RuleFormProps & { active: boolean }> = ({>{rowVirtualizer.getVirtualItems().map((vItem) => {const idx = vItem.index;- const item = data?.[idx];+ const item = data?.get(idx);if (!item) {return (<TableRowdiff --git a/yarn.lock b/yarn.lockindex b89b8026..3f165f8b 100644--- a/yarn.lock+++ b/yarn.lock@@ -3691,6 +3691,11 @@ immer@^9.0.15:resolved "https://registry.npmjs.org/immer/-/immer-9.0.21.tgz#1e025ea31a40f24fb064f1fef23e931496330176"integrity sha512-bc4NBHqOqSfRW7POMkHd51LvClaeMXpm8dx0e8oE2GORbq5aRK7Bxl4FyzVLdGtLmvLKL7BTDBG5ACQm4HWjTA==+immutable@^5.1.1:+ version "5.1.1"+ resolved "https://registry.yarnpkg.com/immutable/-/immutable-5.1.1.tgz#d4cb552686f34b076b3dcf23c4384c04424d8354"+ integrity sha512-3jatXi9ObIsPGr3N5hGw/vWWcTkq6hUYhpQz4k0wLC+owqWi/LiugIw9x0EdNZ2yGedKN/HzePiBvaJRXa0Ujg==+import-fresh@^3.2.1:version "3.3.0"resolved "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz#37162c25fcb9ebaa2e6e53d5b4d88ce17d9e0c2b"