• Stars
    star
    146
  • Rank 252,769 (Top 5 %)
  • Language
    JavaScript
  • Created over 11 years ago
  • Updated about 2 years ago

Reviews

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

Repository Details

Self-balancing binary search tree for Node.js (uses AVL tree)

Binary search trees for Node.js

Note: this module is not actively maintained bar for bug fixes. Its primary use is within NeDB and I do not plan on adding any new features.

Two implementations of binary search tree: basic and AVL (a kind of self-balancing binmary search tree). I wrote this module primarily to store indexes for NeDB (a javascript dependency-less database).

Installation and tests

Package name is binary-search-tree.

npm install binary-search-tree --save

make test

Usage

The API mainly provides 3 functions: insert, search and delete. If you do not create a unique-type binary search tree, you can store multiple pieces of data for the same key. Doing so with a unique-type BST will result in an error being thrown. Data is always returned as an array, and you can delete all data relating to a given key, or just one piece of data.

Values inserted can be anything except undefined.

var BinarySearchTree = require('binary-search-tree').BinarySearchTree
  , AVLTree = require('binary-search-tree').AVLTree   // Same API as BinarySearchTree

// Creating a binary search tree
var bst = new BinarySearchTree();

// Inserting some data
bst.insert(15, 'some data for key 15');
bst.insert(12, 'something else');
bst.insert(18, 'hello');

// You can insert multiple pieces of data for the same key
// if your tree doesn't enforce a unique constraint
bst.insert(18, 'world');

// Retrieving data (always returned as an array of all data stored for this key)
bst.search(15);   // Equal to ['some data for key 15']
bst.search(18);   // Equal to ['hello', 'world']
bst.search(1);    // Equal to []

// Search between bounds with a MongoDB-like query
// Data is returned in key order
// Note the difference between $lt (less than) and $gte (less than OR EQUAL)
bst.betweenBounds({ $lt: 18, $gte: 12});   // Equal to ['something else', 'some data for key 15']

// Deleting all the data relating to a key
bst.delete(15);   // bst.search(15) will now give []
bst.delete(18, 'world');   // bst.search(18) will now give ['hello']

There are three optional parameters you can pass the BST constructor, allowing you to enforce a key-uniqueness constraint, use a custom function to compare keys and use a custom function to check whether values are equal. These parameters are all passed in an object.

Uniqueness

var bst = new BinarySearchTree({ unique: true });
bst.insert(10, 'hello');
bst.insert(10, 'world');   // Will throw an error

Custom key comparison

// Custom key comparison function
// It needs to return a negative number if a is less than b,
// a positive number if a is greater than b
// and 0 if they are equal
// If none is provided, the default one can compare numbers, dates and strings
// which are the most common usecases
function compareKeys (a, b) {
  if (a.age < b.age) { return -1; }
  if (a.age > b.age) { return 1; }
  
  return 0;
}

// Now we can use objects with an 'age' property as keys
var bst = new BinarySearchTree({ compareKeys: compareKeys });
bst.insert({ age: 23 }, 'Mark');
bst.insert({ age: 47 }, 'Franck');

Custom value checking

// Custom value equality checking function used when we try to just delete one piece of data
// Returns true if a and b are considered the same, false otherwise
// The default function is able to compare numbers and strings
function checkValueEquality (a, b) {
  return a.length === b.length;
}
var bst = new BinarySearchTree({ checkValueEquality: checkValueEquality });
bst.insert(10, 'hello');
bst.insert(10, 'world');
bst.insert(10, 'howdoyoudo');

bst.delete(10, 'abcde');
bst.search(10);   // Returns ['howdoyoudo']

License

(The MIT License)

Copyright (c) 2013 Louis Chatriot <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

nedb

The JavaScript Database, for Node.js, nw.js, electron and the browser
JavaScript
13,357
star
2

node-redis-pubsub

Simple pubsub for node using Redis
JavaScript
280
star
3

mongo-edit

A simple REST gui for MongoDB
JavaScript
228
star
4

nedb-to-mongodb

Utility to transfer all your data in a nedb database in a MongoDB collection
JavaScript
85
star
5

nedb-logger

A logger that output message to a file in an nedb-readable format with minimal memory footprint
JavaScript
50
star
6

braindead-ci

JavaScript
48
star
7

connect-nedb-session

NeDB-backed session store for the Connect/Express session middleware
JavaScript
37
star
8

express-group-handlers

Apply a middleware only to a group of route handlers in Express
JavaScript
32
star
9

h4e

Hogan for Express, with support for partials
JavaScript
18
star
10

trello-capture

Chrome extension to take a (partial) screenshot of a webpage and create a new Trello card with it in it
JavaScript
15
star
11

nedb-server

HTTP interface for a NeDB database
JavaScript
12
star
12

M-command

Chrome plugin to get the same behaviour as vim's M command
JavaScript
12
star
13

exec-time

See how much time every step of a node script takes
JavaScript
10
star
14

express-nedb-session

Nedb-backed session store for Express 4 session middleware
JavaScript
9
star
15

taffydb-benchmark

Benchmark of TaffyDB on basic CRUD operations. The benchmark code is the same as the one used for NeDB.
JavaScript
7
star
16

url-shortener

A basic url shortener
JavaScript
5
star
17

raspi-media-center

Media center based on Rasberry Pi, remotely controllable by smartphone through HTTP server
JavaScript
5
star
18

node-pbkdf2

Wrapper to hash and check password with crypto's built-in pbkdf2, abstracting the API change between node v0.8 and v0.10
JavaScript
5
star
19

NodejsStarterKit

Starter kit I use on my side projects to create websites/api with nodejs and express
JavaScript
4
star
20

raycasting

Minimal raycasting 3D engine
JavaScript
3
star
21

Stanford-Classes

My project files for Stanford's online classes
Java
3
star
22

lm-heatmap

Local Motion heatmaps
JavaScript
3
star
23

dotfiles

My dotfiles
Shell
3
star
24

tetris

A small DOM tetris game
JavaScript
2
star
25

data-graphs

Small chart library for use with Local Motion's data reports
JavaScript
2
star
26

peaceful-internet

Remove unneeded attention grabbing from the internet
JavaScript
2
star
27

btc-bot

JavaScript
2
star
28

pipedrive-plus

Set of tools to enhance Pipedrive
JavaScript
2
star
29

snake

A good old snake
JavaScript
1
star
30

jeu-ines

Q&A game for my sister's marriage
JavaScript
1
star
31

raytracing

A minimalist raytracing engine
Python
1
star
32

fundor

Self-updating list of startup that raise money
JavaScript
1
star
33

ml_example

Super basic example to show how machine learning works
JavaScript
1
star
34

mariokart-web-client

JavaScript
1
star
35

advent-of-code

Hopefully I have the time to do it!
Python
1
star
36

gop

Multiplayer real time Go playing server
JavaScript
1
star