Splay Tree Data Structures for TypeScript

1.0.2 · active · verified Wed Apr 22

splaytree-ts is a TypeScript library that provides efficient implementations of Splay Tree data structures, specifically `SplayTreeMap` and `SplayTreeSet`. Splay trees are self-balancing binary search trees with the distinct characteristic that recently accessed elements are more quickly accessible again, offering O(log(n)) amortized time complexity for fundamental operations like insertion, lookup, and removal. The current stable version is 1.0.2. Its key differentiation lies in the splaying heuristic, which optimizes for temporal locality of reference, making it particularly performant for workloads with skewed access patterns. The library supports custom comparison functions and key validation predicates for flexible use with various data types, enhancing its utility beyond simple primitive comparisons.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic usage of SplayTreeSet for number operations and SplayTreeMap with a custom comparison function for object keys.

import { SplayTreeSet, SplayTreeMap } from 'splaytree-ts';

// Example 1: Using SplayTreeSet for numbers
const ages = new SplayTreeSet<number>();
for (const age of [33, 45, 25, 35, 59, 18, 62]) {
  ages.add(age);
}

console.log('Ages in set:', Array.from(ages.values())); // [18, 25, 33, 35, 45, 59, 62]
console.log('First age after 35:', ages.firstAfter(35));  // Expected: 45
console.log('Last age before 33:', ages.lastBefore(33));   // Expected: 25

ages.delete(59);      // true
console.log('Has 59 after deletion:', ages.has(59)); // false

// Example 2: Using SplayTreeMap with custom comparison for objects
interface User { id: number; name: string; }
const users = new SplayTreeMap<number, User>(
  (a, b) => a - b // Compare by user ID
);

users.set(101, { id: 101, name: 'Alice' });
users.set(50, { id: 50, name: 'Bob' });
users.set(200, { id: 200, name: 'Charlie' });

console.log('User with ID 50:', users.get(50)); // { id: 50, name: 'Bob' }

view raw JSON →