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

utils.ts

146 lines3.7 KB

1/**
2 * Simple assertion function for runtime checks.
3 * Throws an error if the condition is false.
4 */
5export function assert(
6 condition: unknown,
7 message?: string
8): asserts condition {
9 if (!condition) {
10 throw new Error(message || `Assertion failed`)
11 }
13​
14/**
15 * A map that returns a default value for keys that are not present.
16 */
17export class DefaultMap<K, V> extends Map<K, V> {
18 constructor(
19 private defaultValue: () => V,
20 entries?: Iterable<[K, V]>
21 ) {
22 super(entries)
23 }
24​
25 get(key: K): V {
26 if (!this.has(key)) {
27 // this.set(key, this.defaultValue())
28 return this.defaultValue()
29 }
30 return super.get(key)!
31 }
32​
33 /**
34 * Update the value for a key using a function.
35 */
36 update(key: K, updater: (value: V) => V): V {
37 const value = this.get(key)
38 const newValue = updater(value)
39 this.set(key, newValue)
40 return newValue
41 }
43​
44// JS engines have various limits on how many args can be passed to a function
45// with a spread operator, so we need to split the operation into chunks
46// 32767 is the max for Chrome 14, all others are higher
47// TODO: investigate the performance of this and other approaches
48const chunkSize = 30000
49export function chunkedArrayPush(array: Array<unknown>, other: Array<unknown>) {
50 if (other.length <= chunkSize) {
51 array.push(...other)
52 } else {
53 for (let i = 0; i < other.length; i += chunkSize) {
54 const chunk = other.slice(i, i + chunkSize)
55 array.push(...chunk)
56 }
57 }
59​
60export function binarySearch<T>(
61 array: Array<T>,
62 value: T,
63 comparator: (a: T, b: T) => number
64): number {
65 let low = 0
66 let high = array.length
67 while (low < high) {
68 const mid = Math.floor((low + high) / 2)
69 const comparison = comparator(array[mid]!, value)
70 if (comparison < 0) {
71 low = mid + 1
72 } else if (comparison > 0) {
73 high = mid
74 } else {
75 return mid
76 }
77 }
78 return low
80​
81/**
82 * Utility for generating unique IDs for objects and values.
83 * Uses WeakMap for object reference tracking and consistent hashing for primitives.
84 */
85export class ObjectIdGenerator {
86 private objectIds = new WeakMap<object, number>()
87 private nextId = 0
88​
89 /**
90 * Get a unique identifier for any value.
91 * - Objects: Uses WeakMap for reference-based identity
92 * - Primitives: Uses consistent string-based hashing
93 */
94 getId(value: any): number {
95 // For primitives, use a simple hash of their string representation
96 if (typeof value !== `object` || value === null) {
97 const str = String(value)
98 let hashValue = 0
99 for (let i = 0; i < str.length; i++) {
100 const char = str.charCodeAt(i)
101 hashValue = (hashValue << 5) - hashValue + char
102 hashValue = hashValue & hashValue // Convert to 32-bit integer
103 }
104 return hashValue
105 }
106​
107 // For objects, use WeakMap to assign unique IDs
108 if (!this.objectIds.has(value)) {
109 this.objectIds.set(value, this.nextId++)
110 }
111 return this.objectIds.get(value)!
112 }
113​
114 /**
115 * Get a string representation of the ID for use in composite keys.
116 */
117 getStringId(value: any): string {
118 if (value === null) return `null`
119 if (value === undefined) return `undefined`
120 if (typeof value !== `object`) return `str_${String(value)}`
121​
122 return `obj_${this.getId(value)}`
123 }
125​
126/**
127 * Global instance for cases where a shared object ID space is needed.
128 */
129export const globalObjectIdGenerator = new ObjectIdGenerator()
130​
131export function* concatIterable<T>(
132 ...iterables: Array<Iterable<T>>
133): Iterable<T> {
134 for (const iterable of iterables) {
135 yield* iterable
136 }
138​
139export function* mapIterable<T, U>(
140 it: Iterable<T>,
141 fn: (t: T) => U
142): Iterable<U> {
143 for (const t of it) {
144 yield fn(t)
145 }