• Stars
    star
    358
  • Rank 116,531 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A purely functional red-black tree data structure

functional-red-black-tree

A fully persistent red-black tree written 100% in JavaScript. Works both in node.js and in the browser via browserify.

Functional (or fully persistent) data structures allow for non-destructive updates. So if you insert an element into the tree, it returns a new tree with the inserted element rather than destructively updating the existing tree in place. Doing this requires using extra memory, and if one were naive it could cost as much as reallocating the entire tree. Instead, this data structure saves some memory by recycling references to previously allocated subtrees. This requires using only O(log(n)) additional memory per update instead of a full O(n) copy.

Some advantages of this is that it is possible to apply insertions and removals to the tree while still iterating over previous versions of the tree. Functional and persistent data structures can also be useful in many geometric algorithms like point location within triangulations or ray queries, and can be used to analyze the history of executing various algorithms. This added power though comes at a cost, since it is generally a bit slower to use a functional data structure than an imperative version. However, if your application needs this behavior then you may consider using this module.

Install

npm install functional-red-black-tree

Example

Here is an example of some basic usage:

//Load the library
var createTree = require("functional-red-black-tree")

//Create a tree
var t1 = createTree()

//Insert some items into the tree
var t2 = t1.insert(1, "foo")
var t3 = t2.insert(2, "bar")

//Remove something
var t4 = t3.remove(1)

API

var createTree = require("functional-red-black-tree")

Overview

Tree methods

var tree = createTree([compare])

Creates an empty functional tree

  • compare is an optional comparison function, same semantics as array.sort()

Returns An empty tree ordered by compare

tree.keys

A sorted array of all the keys in the tree

tree.values

An array array of all the values in the tree

tree.length

The number of items in the tree

tree.get(key)

Retrieves the value associated to the given key

  • key is the key of the item to look up

Returns The value of the first node associated to key

tree.insert(key, value)

Creates a new tree with the new pair inserted.

  • key is the key of the item to insert
  • value is the value of the item to insert

Returns A new tree with key and value inserted

tree.remove(key)

Removes the first item with key in the tree

  • key is the key of the item to remove

Returns A new tree with the given item removed if it exists

tree.find(key)

Returns an iterator pointing to the first item in the tree with key, otherwise null.

tree.ge(key)

Find the first item in the tree whose key is >= key

  • key is the key to search for

Returns An iterator at the given element.

tree.gt(key)

Finds the first item in the tree whose key is > key

  • key is the key to search for

Returns An iterator at the given element

tree.lt(key)

Finds the last item in the tree whose key is < key

  • key is the key to search for

Returns An iterator at the given element

tree.le(key)

Finds the last item in the tree whose key is <= key

  • key is the key to search for

Returns An iterator at the given element

tree.at(position)

Finds an iterator starting at the given element

  • position is the index at which the iterator gets created

Returns An iterator starting at position

tree.begin

An iterator pointing to the first element in the tree

tree.end

An iterator pointing to the last element in the tree

tree.forEach(visitor(key,value)[, lo[, hi]])

Walks a visitor function over the nodes of the tree in order.

  • visitor(key,value) is a callback that gets executed on each node. If a truthy value is returned from the visitor, then iteration is stopped.
  • lo is an optional start of the range to visit (inclusive)
  • hi is an optional end of the range to visit (non-inclusive)

Returns The last value returned by the callback

tree.root

Returns the root node of the tree

Node properties

Each node of the tree has the following properties:

node.key

The key associated to the node

node.value

The value associated to the node

node.left

The left subtree of the node

node.right

The right subtree of the node

Iterator methods

iter.key

The key of the item referenced by the iterator

iter.value

The value of the item referenced by the iterator

iter.node

The value of the node at the iterator's current position. null is iterator is node valid.

iter.tree

The tree associated to the iterator

iter.index

Returns the position of this iterator in the sequence.

iter.valid

Checks if the iterator is valid

iter.clone()

Makes a copy of the iterator

iter.remove()

Removes the item at the position of the iterator

Returns A new binary search tree with iter's item removed

iter.update(value)

Updates the value of the node in the tree at this iterator

Returns A new binary search tree with the corresponding node updated

iter.next()

Advances the iterator to the next position

iter.prev()

Moves the iterator backward one element

iter.hasNext

If true, then the iterator is not at the end of the sequence

iter.hasPrev

If true, then the iterator is not at the beginning of the sequence

Credits

(c) 2013 Mikola Lysenko. MIT License

More Repositories

1

l1-path-finder

πŸ—Ί Fast path planning for 2D grids
JavaScript
471
star
2

vectorize-text

Turns a text string into a 2D poly line
JavaScript
303
star
3

static-kdtree

A static kdtree data structure
JavaScript
302
star
4

orthogami

Orthogonal polyhedra origami
JavaScript
279
star
5

box-intersect

πŸ“¦ Any dimensional box intersection
JavaScript
271
star
6

robust-point-in-polygon

Exactly test if a point is inside, outside or on the boundary of a polygon
JavaScript
229
star
7

cdt2d

2D constrained Delaunay triangulation
JavaScript
223
star
8

mikolalysenko.github.com

JavaScript
210
star
9

laplacian-deformation

Laplacian mesh deformation
C++
209
star
10

robust-arithmetic-notes

Tutorial on robust arithmetic in JavaScript
JavaScript
198
star
11

isosurface

Isosurface polygonizer algorithms
JavaScript
166
star
12

mudb

Low latency state replication for the web
TypeScript
165
star
13

delaunay-triangulate

Easy to use robust Delaunay triangulation
JavaScript
153
star
14

game-shell

Ready to go JavaScript shell for games or other interactive demos
JavaScript
118
star
15

patcher.js

JSON diffing and patching library
JavaScript
112
star
16

electron-recorder

Record animations using Electron
JavaScript
108
star
17

surface-nets

Arbitrary dimensional level sets
JavaScript
96
star
18

binary-search-bounds

Better binary searching
JavaScript
88
star
19

dynamic-forest

Maintain a dynamic spanning forest of a graph under edge insertions and deletions
JavaScript
84
star
20

uniq

Removes duplicate items from an array in place
JavaScript
81
star
21

NodeMinecraftThing

Javascript MMO framework
JavaScript
78
star
22

pitch-shift

Variable speed pitch shifter written in JavaScript
JavaScript
78
star
23

refine-mesh

Iterative mesh refinement
JavaScript
77
star
24

box-intersect-benchmark

Box intersection benchmark
JavaScript
74
star
25

typedarray-pool

Reuse typed arrays
JavaScript
74
star
26

rectangle-decomposition

Computes a minimal rectangular decomposition of a rectilinear polygon
JavaScript
71
star
27

conway-hart

A port of George Hart's implementation/extension of Conway's polyhedral notation to CommonJS
JavaScript
69
star
28

femgl

WebGL finite element viewer
JavaScript
68
star
29

interval-tree-1d

1D interval tree
JavaScript
67
star
30

voxel-mipmap-demo

Demo of mipmapping for voxel terrain
JavaScript
66
star
31

alpha-shape

Any dimensional alpha shapes
JavaScript
66
star
32

simplicial-complex

Tools for manipulating simplicial complexes in JavaScript
JavaScript
63
star
33

mespeak

NPM entry for mespeak for easier installation and usage in browserify
JavaScript
62
star
34

detect-pitch

Detects the pitch of an audio snippet
JavaScript
61
star
35

drag-and-drop-files

Handle file drag-and-drop events without all the Yak shaving
JavaScript
55
star
36

vertex-ao

Vertex based ambient occlusion calculation for meshes
JavaScript
53
star
37

bit-twiddle

Bit twidling hacks for node.js
JavaScript
53
star
38

mouse-wheel

Speed controlled mouse scrolling
JavaScript
50
star
39

to-px

Convert any CSS unit to logical pixels (aka "px")
JavaScript
48
star
40

voronoi-diagram

n-dimensional voronoi diagram constructor
JavaScript
46
star
41

local-perception-filter-demo

Demonstration of local perception filters in a browser
JavaScript
46
star
42

monotone-convex-hull-2d

Robust and fast 2D convex hull
JavaScript
44
star
43

clean-pslg

Clean up messy planar straight line graphs
JavaScript
44
star
44

greedy-mesher

Greedy mesh compiler
JavaScript
43
star
45

ndarray-experiments

Multidimensional typed arrays in JS
JavaScript
42
star
46

glsl-read-float

Read floating point values back from WebGL
JavaScript
41
star
47

a-big-triangle

Draws a big triangle onto the screen
JavaScript
41
star
48

ao-mesher

Voxel mesher with ambient occlusion
JavaScript
40
star
49

convex-hull

Any dimensional convex hull
JavaScript
36
star
50

stft

Short time Fourier transform
JavaScript
34
star
51

taubin-smooth

Taubin's mesh smoothing algorithm implemented in JavaScript
HTML
34
star
52

plastimesh

πŸ‘Ύ A free form mesh sculpting tool
JavaScript
34
star
53

3d-view-controls

A camera with input hooks for basic 3D projects
JavaScript
34
star
54

orbit-camera

Orbit camera for 3D scenes
JavaScript
33
star
55

LudumDare23MMO

LudumDare23 MMO source code (rebuilt to remove database stuff)
JavaScript
33
star
56

ndarray-project-list

List of stuff todo with ndarrays
33
star
57

voxelize

Voxelizes a triangulated mesh into an ndarray
JavaScript
32
star
58

gif-3d

3D gif visualizer
JavaScript
29
star
59

haar-tree-3d

3D Wavelet Rasterization
JavaScript
29
star
60

mouse-event

Cross browser mouse event property access
JavaScript
28
star
61

strongly-connected-components

Computes the strongly connected components of a directed graph
JavaScript
27
star
62

union-find

A basic union-find data structure for node.js
JavaScript
26
star
63

0fpsBlog

Code and examples for 0fps blog
JavaScript
25
star
64

point-in-region

Fast and exact point in region location
JavaScript
25
star
65

node-latex

node.js wrapper for LaTeX
JavaScript
25
star
66

incremental-delaunay

Constructs a Delaunay triangulation for a collection of points
JavaScript
24
star
67

angle

Almost Native Graphics Layer Engine (local fork)
C++
24
star
68

bibtex-parser

A CommonJS port of BibTeX-js
JavaScript
24
star
69

count-min-sketch

Count-Min Sketch Data Structure
JavaScript
24
star
70

bound-points

Find a bounding box for a set of points
JavaScript
23
star
71

MineHack

WebGL based AJAX videogame -- with MMO, Minecraft and Roguelike elements.
C
23
star
72

robust-orientation

Robustly computes the orientation of a tuple of points
JavaScript
23
star
73

lpf-ctf

Multiplayer capture the flag demo
JavaScript
23
star
74

parse-obj

Parses a .OBJ file
JavaScript
23
star
75

cubic-hermite

Cubic hermite interpolation
JavaScript
22
star
76

angle-normals

Compute mesh normals using angle weights
JavaScript
22
star
77

ao-shader

Ambient occlusion shader for ao-mesher
JavaScript
22
star
78

svg-3d-simplicial-complex

Renders a simplicial complex to a list of polygons in SVG
JavaScript
22
star
79

ndarray-tutorial

Guide to ndarrays
21
star
80

mesh-fixer

Fixes holes in 3D meshes
HTML
20
star
81

functional-priority-queue

A functional priority queue in JavaScript
JavaScript
20
star
82

3p

Progressive triangle streams
JavaScript
20
star
83

bunny

The Stanford bunny
19
star
84

ndpack-image

Package an image into a requireable module
JavaScript
19
star
85

gl-modules

A modular approach to WebGL programming
19
star
86

csr-matrix

Compressed sparse row matrix for node.js
JavaScript
19
star
87

contour2d

Extracts a rectilinear polygon contour from a binary image
JavaScript
18
star
88

mathmode

Turns LaTeX math mode expressions into images
JavaScript
18
star
89

triangulate-polyline

Triangulates a complex polygon
JavaScript
18
star
90

poly-bool

Exact polygon boolean operations
JavaScript
18
star
91

filtered-vector

Path smoothing for vector valued input curves
JavaScript
18
star
92

gl-render-text

Renders text to a WebGL texture
JavaScript
17
star
93

differential-growth

Differential growth, inspired by @inconvergent
JavaScript
17
star
94

point-in-big-polygon

Industrial strength point in polygon test
JavaScript
17
star
95

vishull2d

Visible regions for 2D poly-lines
JavaScript
17
star
96

normals

Computes normals for triangulated meshes
JavaScript
17
star
97

commutative-rendering

Ideas about modular graphical rendering
16
star
98

vj-stuff

Stream of consciousness programmed WebGL visualizations
JavaScript
16
star
99

split-polygon

Splits a convex polygon by a plane
JavaScript
16
star
100

control-flow

Control flow graph and 3AC form for JavaScript programs
JavaScript
16
star