or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

core-utilities.mddata-structures.mddevelopment-utilities.mddom-styling.mdfunctional-programming.mdindex.mdnetwork-fetch.mdperformance-crypto.mdtext-unicode.mduser-agent-browser.md
tile.json

data-structures.mddocs/

Data Structures

Specialized data structure implementations including Heap, CircularBuffer, IntegerBufferSet, and PrefixIntervalTree for advanced algorithmic operations.

Capabilities

Heap

Binary heap implementation for priority queue operations with customizable comparison.

const Heap = require('fbjs/lib/Heap');

/**
 * Binary heap data structure for priority queue operations
 */
class Heap {
  /**
   * Creates a new heap
   * @param items - Optional array of initial items
   * @param comparator - Optional comparison function (a, b) => number
   */
  constructor(items?: Array<any>, comparator?: (a: any, b: any) => number);
  
  /**
   * Checks if heap is empty
   * @returns True if heap contains no elements
   */
  empty(): boolean;
  
  /**
   * Removes and returns the minimum element (or maximum if custom comparator)
   * @returns The top element of the heap
   */
  pop(): any;
  
  /**
   * Adds an item to the heap
   * @param item - Item to add to heap
   */
  push(item: any): void;
  
  /**
   * Returns the number of elements in the heap
   * @returns Size of heap
   */
  size(): number;
  
  /**
   * Returns the minimum element (or maximum if custom comparator) without removing it
   * @returns The top element of the heap
   */
  peek(): any;
}

Usage Examples:

const Heap = require('fbjs/lib/Heap');

// Min heap (default)
const minHeap = new Heap();
minHeap.push(5);
minHeap.push(2);
minHeap.push(8);
minHeap.push(1);

console.log(minHeap.peek()); // 1 (minimum)
console.log(minHeap.pop());  // 1
console.log(minHeap.pop());  // 2

// Max heap with custom comparator
const maxHeap = new Heap([], (a, b) => b - a);
maxHeap.push(5);
maxHeap.push(2);
maxHeap.push(8);
maxHeap.push(1);

console.log(maxHeap.peek()); // 8 (maximum)
console.log(maxHeap.pop());  // 8
console.log(maxHeap.pop());  // 5

// Priority queue for objects
const taskHeap = new Heap([], (a, b) => a.priority - b.priority);
taskHeap.push({ name: 'Low priority task', priority: 3 });
taskHeap.push({ name: 'High priority task', priority: 1 });
taskHeap.push({ name: 'Medium priority task', priority: 2 });

const nextTask = taskHeap.pop(); // { name: 'High priority task', priority: 1 }

CircularBuffer

Fixed-size circular buffer implementation for efficient FIFO operations.

const CircularBuffer = require('fbjs/lib/CircularBuffer');

/**
 * Fixed-size circular buffer data structure
 */
class CircularBuffer {
  /**
   * Creates a new circular buffer
   * @param capacity - Maximum number of elements the buffer can hold
   */
  constructor(capacity: number);
  
  /**
   * Adds an element to the buffer
   * If buffer is full, overwrites the oldest element
   * @param element - Element to add
   */
  push(element: any): void;
  
  /**
   * Removes and returns the oldest element
   * @returns The oldest element or undefined if buffer is empty
   */
  shift(): any;
  
  /**
   * Returns the number of elements currently in the buffer
   * @returns Current size of buffer
   */
  size(): number;
  
  /**
   * Returns the maximum capacity of the buffer
   * @returns Buffer capacity
   */
  capacity(): number;
  
  /**
   * Checks if buffer is empty
   * @returns True if buffer contains no elements
   */
  isEmpty(): boolean;
  
  /**
   * Checks if buffer is at full capacity
   * @returns True if buffer is full
   */
  isFull(): boolean;
  
  /**
   * Gets element at specific index without removing it
   * @param index - Index to access (0 is oldest element)
   * @returns Element at index or undefined
   */
  get(index: number): any;
  
  /**
   * Clears all elements from the buffer
   */
  clear(): void;
}

Usage Examples:

const CircularBuffer = require('fbjs/lib/CircularBuffer');

// Create buffer with capacity of 3
const buffer = new CircularBuffer(3);

// Add elements
buffer.push('first');
buffer.push('second');
buffer.push('third');

console.log(buffer.size()); // 3
console.log(buffer.isFull()); // true

// Add fourth element (overwrites 'first')
buffer.push('fourth');

console.log(buffer.get(0)); // 'second' (now oldest)
console.log(buffer.shift()); // 'second'
console.log(buffer.shift()); // 'third'
console.log(buffer.shift()); // 'fourth'
console.log(buffer.isEmpty()); // true

// Use as sliding window
const slidingWindow = new CircularBuffer(5);
for (let i = 0; i < 10; i++) {
  slidingWindow.push(i);
  if (slidingWindow.isFull()) {
    // Process window of last 5 values
    const window = [];
    for (let j = 0; j < slidingWindow.size(); j++) {
      window.push(slidingWindow.get(j));
    }
    console.log('Window:', window);
  }
}

IntegerBufferSet

Set implementation optimized for integer values using buffer storage.

const IntegerBufferSet = require('fbjs/lib/IntegerBufferSet');

/**
 * Set implementation for integers using buffer storage for efficiency
 */
class IntegerBufferSet {
  /**
   * Creates a new integer buffer set
   * @param maxValue - Maximum integer value that can be stored
   */
  constructor(maxValue: number);
  
  /**
   * Adds an integer to the set
   * @param value - Integer value to add (must be >= 0 and <= maxValue)
   */
  add(value: number): void;
  
  /**
   * Removes an integer from the set
   * @param value - Integer value to remove
   */
  delete(value: number): void;
  
  /**
   * Checks if integer is in the set
   * @param value - Integer value to check
   * @returns True if value is in set
   */
  has(value: number): boolean;
  
  /**
   * Returns the number of integers in the set
   * @returns Size of set
   */
  size(): number;
  
  /**
   * Removes all integers from the set
   */
  clear(): void;
  
  /**
   * Checks if set is empty
   * @returns True if set contains no integers
   */
  isEmpty(): boolean;
  
  /**
   * Returns an array of all integers in the set
   * @returns Array of integers in set
   */
  toArray(): Array<number>;
  
  /**
   * Executes callback for each integer in the set
   * @param callback - Function to call for each integer
   */
  forEach(callback: (value: number) => void): void;
}

Usage Examples:

const IntegerBufferSet = require('fbjs/lib/IntegerBufferSet');

// Create set for integers 0-999
const idSet = new IntegerBufferSet(999);

// Add user IDs
idSet.add(123);
idSet.add(456);
idSet.add(789);
idSet.add(123); // Duplicate, no effect

console.log(idSet.has(123)); // true
console.log(idSet.has(999)); // false
console.log(idSet.size()); // 3

// Process all IDs
idSet.forEach(id => {
  console.log('Processing user ID:', id);
});

// Convert to array for sorting
const sortedIds = idSet.toArray().sort((a, b) => a - b);
console.log('Sorted IDs:', sortedIds); // [123, 456, 789]

PrefixIntervalTree

Interval tree optimized for prefix matching operations.

const PrefixIntervalTree = require('fbjs/lib/PrefixIntervalTree');

/**
 * Interval tree data structure optimized for prefix matching
 */
class PrefixIntervalTree {
  /**
   * Creates a new prefix interval tree
   */
  constructor();
  
  /**
   * Adds an interval to the tree
   * @param start - Start position of interval
   * @param end - End position of interval
   * @param data - Data associated with this interval
   */
  addInterval(start: number, end: number, data: any): void;
  
  /**
   * Finds all intervals that contain the given point
   * @param point - Point to search for
   * @returns Array of interval data that contain the point
   */
  queryPoint(point: number): Array<any>;
  
  /**
   * Finds all intervals that overlap with the given range
   * @param start - Start of query range
   * @param end - End of query range
   * @returns Array of interval data that overlap with the range
   */
  queryRange(start: number, end: number): Array<any>;
  
  /**
   * Finds all intervals that have the given prefix
   * @param prefix - Prefix to match against interval start positions
   * @returns Array of interval data with matching prefix
   */
  queryPrefix(prefix: string): Array<any>;
  
  /**
   * Removes all intervals from the tree
   */
  clear(): void;
  
  /**
   * Returns the number of intervals in the tree
   * @returns Number of intervals
   */
  size(): number;
  
  /**
   * Checks if tree is empty
   * @returns True if tree contains no intervals
   */
  isEmpty(): boolean;
}

Usage Examples:

const PrefixIntervalTree = require('fbjs/lib/PrefixIntervalTree');

// Create tree for text highlighting ranges
const highlightTree = new PrefixIntervalTree();

// Add highlighting intervals with metadata
highlightTree.addInterval(10, 20, { type: 'keyword', color: 'blue' });
highlightTree.addInterval(15, 25, { type: 'string', color: 'green' });
highlightTree.addInterval(30, 40, { type: 'comment', color: 'gray' });

// Find what should be highlighted at cursor position 18
const highlightsAtCursor = highlightTree.queryPoint(18);
// Returns: [{ type: 'keyword', color: 'blue' }, { type: 'string', color: 'green' }]

// Find all overlapping highlights in a range
const overlappingHighlights = highlightTree.queryRange(12, 35);
// Returns highlights that overlap with range 12-35

// Use for prefix matching in autocomplete
const autocompleteTree = new PrefixIntervalTree();
autocompleteTree.addInterval(0, 0, 'apple');
autocompleteTree.addInterval(0, 0, 'application');
autocompleteTree.addInterval(0, 0, 'apply');

// Find completions with prefix
const completions = autocompleteTree.queryPrefix('app');
// Returns: ['apple', 'application', 'apply']

Additional Data Structures

More specialized data structure implementations for advanced use cases.

const CircularBuffer = require('fbjs/lib/CircularBuffer');

/**
 * Fixed-size circular buffer implementation
 * Overwrites oldest entries when buffer is full
 */
class CircularBuffer<T> {
  /**
   * Creates a circular buffer with fixed capacity
   * @param capacity - Maximum number of elements
   */
  constructor(capacity: number);
  
  /**
   * Adds element to buffer (overwrites oldest if full)
   * @param item - Item to add
   */
  push(item: T): void;
  
  /**
   * Removes and returns the oldest element
   * @returns Oldest element or undefined if empty
   */
  shift(): ?T;
  
  /**
   * Gets element at index (0 = oldest)
   * @param index - Index to access
   * @returns Element at index or undefined
   */
  get(index: number): ?T;
  
  /**
   * Returns current number of elements
   * @returns Number of elements in buffer
   */
  size(): number;
  
  /**
   * Returns maximum capacity
   * @returns Buffer capacity
   */
  capacity(): number;
  
  /**
   * Checks if buffer is empty
   * @returns True if buffer contains no elements
   */
  isEmpty(): boolean;
  
  /**
   * Checks if buffer is at full capacity
   * @returns True if buffer is full
   */
  isFull(): boolean;
  
  /**
   * Removes all elements from buffer
   */
  clear(): void;
  
  /**
   * Converts buffer contents to array
   * @returns Array of elements (oldest first)
   */
  toArray(): Array<T>;
}

Usage Examples:

const CircularBuffer = require('fbjs/lib/CircularBuffer');

// Circular buffer for recent activity log
const activityLog = new CircularBuffer(100); // Keep last 100 activities

function logActivity(message) {
  activityLog.push({
    timestamp: Date.now(),
    message: message
  });
}

// Log some activities
logActivity('User logged in');
logActivity('User opened document');
logActivity('User saved changes');

// Access recent activities
console.log('Recent activity count:', activityLog.size());
console.log('Oldest activity:', activityLog.get(0));
console.log('All activities:', activityLog.toArray());

// Buffer metrics tracking
const metricsBuffer = new CircularBuffer(50);
function recordMetric(value) {
  metricsBuffer.push({
    value: value,
    timestamp: Date.now()
  });
  
  // Calculate rolling average
  if (metricsBuffer.size() >= 10) {
    const recent = metricsBuffer.toArray().slice(-10);
    const average = recent.reduce((sum, m) => sum + m.value, 0) / recent.length;
    console.log('Rolling average:', average.toFixed(2));
  }
}