@tanstack/db
Version:
A reactive client store for building super fast apps on sync
206 lines (205 loc) • 10.8 kB
TypeScript
type EditRangeResult<V, R = number> = {
value?: V;
break?: R;
delete?: boolean;
};
/**
* A reasonably fast collection of key-value pairs with a powerful API.
* Largely compatible with the standard Map. BTree is a B+ tree data structure,
* so the collection is sorted by key.
*
* B+ trees tend to use memory more efficiently than hashtables such as the
* standard Map, especially when the collection contains a large number of
* items. However, maintaining the sort order makes them modestly slower:
* O(log size) rather than O(1). This B+ tree implementation supports O(1)
* fast cloning. It also supports freeze(), which can be used to ensure that
* a BTree is not changed accidentally.
*
* Confusingly, the ES6 Map.forEach(c) method calls c(value,key) instead of
* c(key,value), in contrast to other methods such as set() and entries()
* which put the key first. I can only assume that the order was reversed on
* the theory that users would usually want to examine values and ignore keys.
* BTree's forEach() therefore works the same way, but a second method
* `.forEachPair((key,value)=>{...})` is provided which sends you the key
* first and the value second; this method is slightly faster because it is
* the "native" for-each method for this class.
*
* Out of the box, BTree supports keys that are numbers, strings, arrays of
* numbers/strings, Date, and objects that have a valueOf() method returning a
* number or string. Other data types, such as arrays of Date or custom
* objects, require a custom comparator, which you must pass as the second
* argument to the constructor (the first argument is an optional list of
* initial items). Symbols cannot be used as keys because they are unordered
* (one Symbol is never "greater" or "less" than another).
*
* @example
* Given a {name: string, age: number} object, you can create a tree sorted by
* name and then by age like this:
*
* var tree = new BTree(undefined, (a, b) => {
* if (a.name > b.name)
* return 1; // Return a number >0 when a > b
* else if (a.name < b.name)
* return -1; // Return a number <0 when a < b
* else // names are equal (or incomparable)
* return a.age - b.age; // Return >0 when a.age > b.age
* });
*
* tree.set({name:"Bill", age:17}, "happy");
* tree.set({name:"Fran", age:40}, "busy & stressed");
* tree.set({name:"Bill", age:55}, "recently laid off");
* tree.forEachPair((k, v) => {
* console.log(`Name: ${k.name} Age: ${k.age} Status: ${v}`);
* });
*
* @description
* The "range" methods (`forEach, forRange, editRange`) will return the number
* of elements that were scanned. In addition, the callback can return {break:R}
* to stop early and return R from the outer function.
*
* - TODO: Test performance of preallocating values array at max size
* - TODO: Add fast initialization when a sorted array is provided to constructor
*
* For more documentation see https://github.com/qwertie/btree-typescript
*
* Are you a C# developer? You might like the similar data structures I made for C#:
* BDictionary, BList, etc. See http://core.loyc.net/collections/
*
* @author David Piepgrass
*/
export declare class BTree<K = any, V = any> {
private _root;
_size: number;
_maxNodeSize: number;
/**
* provides a total order over keys (and a strict partial order over the type K)
* @returns a negative value if a < b, 0 if a === b and a positive value if a > b
*/
_compare: (a: K, b: K) => number;
/**
* Initializes an empty B+ tree.
* @param compare Custom function to compare pairs of elements in the tree.
* If not specified, defaultComparator will be used which is valid as long as K extends DefaultComparable.
* @param entries A set of key-value pairs to initialize the tree
* @param maxNodeSize Branching factor (maximum items or children per node)
* Must be in range 4..256. If undefined or <4 then default is used; if >256 then 256.
*/
constructor(compare: (a: K, b: K) => number, entries?: Array<[K, V]>, maxNodeSize?: number);
/** Gets the number of key-value pairs in the tree. */
get size(): number;
/** Gets the number of key-value pairs in the tree. */
get length(): number;
/** Returns true iff the tree contains no key-value pairs. */
get isEmpty(): boolean;
/** Releases the tree so that its size is 0. */
clear(): void;
/**
* Finds a pair in the tree and returns the associated value.
* @param defaultValue a value to return if the key was not found.
* @returns the value, or defaultValue if the key was not found.
* @description Computational complexity: O(log size)
*/
get(key: K, defaultValue?: V): V | undefined;
/**
* Adds or overwrites a key-value pair in the B+ tree.
* @param key the key is used to determine the sort order of
* data in the tree.
* @param value data to associate with the key (optional)
* @param overwrite Whether to overwrite an existing key-value pair
* (default: true). If this is false and there is an existing
* key-value pair then this method has no effect.
* @returns true if a new key-value pair was added.
* @description Computational complexity: O(log size)
* Note: when overwriting a previous entry, the key is updated
* as well as the value. This has no effect unless the new key
* has data that does not affect its sort order.
*/
set(key: K, value: V, overwrite?: boolean): boolean;
/**
* Returns true if the key exists in the B+ tree, false if not.
* Use get() for best performance; use has() if you need to
* distinguish between "undefined value" and "key not present".
* @param key Key to detect
* @description Computational complexity: O(log size)
*/
has(key: K): boolean;
/**
* Removes a single key-value pair from the B+ tree.
* @param key Key to find
* @returns true if a pair was found and removed, false otherwise.
* @description Computational complexity: O(log size)
*/
delete(key: K): boolean;
/** Returns the maximum number of children/values before nodes will split. */
get maxNodeSize(): number;
/** Gets the lowest key in the tree. Complexity: O(log size) */
minKey(): K | undefined;
/** Gets the highest key in the tree. Complexity: O(1) */
maxKey(): K | undefined;
/** Gets an array of all keys, sorted */
keysArray(): K[];
/** Returns the next pair whose key is larger than the specified key (or undefined if there is none).
* If key === undefined, this function returns the lowest pair.
* @param key The key to search for.
* @param reusedArray Optional array used repeatedly to store key-value pairs, to
* avoid creating a new array on every iteration.
*/
nextHigherPair(key: K | undefined, reusedArray?: [K, V]): [K, V] | undefined;
/** Returns the next key larger than the specified key, or undefined if there is none.
* Also, nextHigherKey(undefined) returns the lowest key.
*/
nextHigherKey(key: K | undefined): K | undefined;
/** Returns the next pair whose key is smaller than the specified key (or undefined if there is none).
* If key === undefined, this function returns the highest pair.
* @param key The key to search for.
* @param reusedArray Optional array used repeatedly to store key-value pairs, to
* avoid creating a new array each time you call this method.
*/
nextLowerPair(key: K | undefined, reusedArray?: [K, V]): [K, V] | undefined;
/** Returns the next key smaller than the specified key, or undefined if there is none.
* Also, nextLowerKey(undefined) returns the highest key.
*/
nextLowerKey(key: K | undefined): K | undefined;
/** Adds all pairs from a list of key-value pairs.
* @param pairs Pairs to add to this tree. If there are duplicate keys,
* later pairs currently overwrite earlier ones (e.g. [[0,1],[0,7]]
* associates 0 with 7.)
* @param overwrite Whether to overwrite pairs that already exist (if false,
* pairs[i] is ignored when the key pairs[i][0] already exists.)
* @returns The number of pairs added to the collection.
* @description Computational complexity: O(pairs.length * log(size + pairs.length))
*/
setPairs(pairs: Array<[K, V]>, overwrite?: boolean): number;
forRange(low: K, high: K, includeHigh: boolean, onFound?: (k: K, v: V, counter: number) => void, initialCounter?: number): number;
/**
* Scans and potentially modifies values for a subsequence of keys.
* Note: the callback `onFound` should ideally be a pure function.
* Specfically, it must not insert items, call clone(), or change
* the collection except via return value; out-of-band editing may
* cause an exception or may cause incorrect data to be sent to
* the callback (duplicate or missed items). It must not cause a
* clone() of the collection, otherwise the clone could be modified
* by changes requested by the callback.
* @param low The first key scanned will be greater than or equal to `low`.
* @param high Scanning stops when a key larger than this is reached.
* @param includeHigh If the `high` key is present, `onFound` is called for
* that final pair if and only if this parameter is true.
* @param onFound A function that is called for each key-value pair. This
* function can return `{value:v}` to change the value associated
* with the current key, `{delete:true}` to delete the current pair,
* `{break:R}` to stop early with result R, or it can return nothing
* (undefined or {}) to cause no effect and continue iterating.
* `{break:R}` can be combined with one of the other two commands.
* The third argument `counter` is the number of items iterated
* previously; it equals 0 when `onFound` is called the first time.
* @returns The number of values scanned, or R if the callback returned
* `{break:R}` to stop early.
* @description
* Computational complexity: O(number of items scanned + log size)
* Note: if the tree has been cloned with clone(), any shared
* nodes are copied before `onFound` is called. This takes O(n) time
* where n is proportional to the amount of shared data scanned.
*/
editRange<R = V>(low: K, high: K, includeHigh: boolean, onFound: (k: K, v: V, counter: number) => EditRangeResult<V, R> | void, initialCounter?: number): R | number;
}
export {};