Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

utils.ts

163 lines4.4 KB

1import murmurhash from "murmurhash-js"
2​
3/**
4 * A map that returns a default value for keys that are not present.
5 */
6export class DefaultMap<K, V> extends Map<K, V> {
7 constructor(
8 private defaultValue: () => V,
9 entries?: Iterable<[K, V]>
10 ) {
11 super(entries)
12 }
13​
14 get(key: K): V {
15 if (!this.has(key)) {
16 this.set(key, this.defaultValue())
17 }
18 return super.get(key)!
19 }
20​
21 /**
22 * Update the value for a key using a function.
23 */
24 update(key: K, updater: (value: V) => V): V {
25 const value = this.get(key)
26 const newValue = updater(value)
27 this.set(key, newValue)
28 return newValue
29 }
31​
32// JS engines have various limits on how many args can be passed to a function
33// with a spread operator, so we need to split the operation into chunks
34// 32767 is the max for Chrome 14, all others are higher
35// TODO: investigate the performance of this and other approaches
36const chunkSize = 30000
37export function chunkedArrayPush(array: Array<unknown>, other: Array<unknown>) {
38 if (other.length <= chunkSize) {
39 array.push(...other)
40 } else {
41 for (let i = 0; i < other.length; i += chunkSize) {
42 const chunk = other.slice(i, i + chunkSize)
43 array.push(...chunk)
44 }
45 }
47​
48const hashCache = new WeakMap()
49​
50/**
51 * Replacer function for JSON.stringify that converts unsupported types to strings
52 */
53function hashReplacer(_key: string, value: any): any {
54 if (typeof value === `bigint`) {
55 return String(value)
56 } else if (typeof value === `symbol`) {
57 return String(value)
58 } else if (typeof value === `function`) {
59 return String(value)
60 } else if (value === undefined) {
61 return `undefined`
62 } else if (value instanceof Map) {
63 return `Map(${JSON.stringify(Array.from(value.entries()), hashReplacer)})`
64 } else if (value instanceof Set) {
65 return `Set(${JSON.stringify(Array.from(value.values()), hashReplacer)})`
66 }
67 return value
69​
70/**
71 * A hash method that caches the hash of a value in a week map
72 */
73export function hash(data: any): string {
74 if (
75 data === null ||
76 data === undefined ||
77 (typeof data !== `object` && typeof data !== `function`)
78 ) {
79 // Can't be cached in the weak map because it's not an object
80 const serialized = JSON.stringify(data, hashReplacer)
81 return murmurhash.murmur3(serialized).toString(16)
82 }
83​
84 if (hashCache.has(data)) {
85 return hashCache.get(data)
86 }
87​
88 const serialized = JSON.stringify(data, hashReplacer)
89 const hashValue = murmurhash.murmur3(serialized).toString(16)
90 hashCache.set(data, hashValue)
91 return hashValue
93​
94export function binarySearch<T>(
95 array: Array<T>,
96 value: T,
97 comparator: (a: T, b: T) => number
98): number {
99 let low = 0
100 let high = array.length
101 while (low < high) {
102 const mid = Math.floor((low + high) / 2)
103 const comparison = comparator(array[mid]!, value)
104 if (comparison < 0) {
105 low = mid + 1
106 } else if (comparison > 0) {
107 high = mid
108 } else {
109 return mid
110 }
111 }
112 return low
114​
115/**
116 * Utility for generating unique IDs for objects and values.
117 * Uses WeakMap for object reference tracking and consistent hashing for primitives.
118 */
119export class ObjectIdGenerator {
120 private objectIds = new WeakMap<object, number>()
121 private nextId = 0
122​
123 /**
124 * Get a unique identifier for any value.
125 * - Objects: Uses WeakMap for reference-based identity
126 * - Primitives: Uses consistent string-based hashing
127 */
128 getId(value: any): number {
129 // For primitives, use a simple hash of their string representation
130 if (typeof value !== `object` || value === null) {
131 const str = String(value)
132 let hashValue = 0
133 for (let i = 0; i < str.length; i++) {
134 const char = str.charCodeAt(i)
135 hashValue = (hashValue << 5) - hashValue + char
136 hashValue = hashValue & hashValue // Convert to 32-bit integer
137 }
138 return hashValue
139 }
140​
141 // For objects, use WeakMap to assign unique IDs
142 if (!this.objectIds.has(value)) {
143 this.objectIds.set(value, this.nextId++)
144 }
145 return this.objectIds.get(value)!
146 }
147​
148 /**
149 * Get a string representation of the ID for use in composite keys.
150 */
151 getStringId(value: any): string {
152 if (value === null) return `null`
153 if (value === undefined) return `undefined`
154 if (typeof value !== `object`) return `str_${String(value)}`
155​
156 return `obj_${this.getId(value)}`
157 }
159​
160/**
161 * Global instance for cases where a shared object ID space is needed.
162 */
163export const globalObjectIdGenerator = new ObjectIdGenerator()