Code Monkey home page Code Monkey logo

node-binary-search-tree's Introduction

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.

node-binary-search-tree's People

Contributors

hanwencheng avatar jamesmgreene avatar louischatriot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-binary-search-tree's Issues

BetweenBounds() can't be used to fetch all values

Thanks for your beautiful lib. However, I'd expect betweenBounds() to return all values in sorted order unless an argument is passed.

Simple test case:

AVLTree = require('binary-search-tree').AVLTree
tree  = new AVLTree()
tree.insert 15, 'some data for key 15'
console.log tree.betweenBounds()

Note that passing an empty object {} seems to fix the issue, so it's a very minor bug.

Util dependency not specified in package.json

In the file lib/avltree.js there is a require for util, but this lib was never specified as a dependency in package.json.

When trying to use node-binary-search-tree on a project that don't have util as a dependency it's generate an error.

getFirst and getLast functions

Thanks for the great module! I get that you're not maintaining it anymore, so instead of a Pull request, I'm just going to leave this here for any future coders who happen to wander by.

I needed the ability to get the first & last n elements from the tree, regardless of value, and didn't see a function that could do that. I started using the betweenBounds function, but had to pass {} to that to get the whole tree, then only use 10 (the number I needed) out of thousands of elements. Since my code needs to be as efficient as possible, I built a few functions into this module to simply walk the tree and pull out the first/last n elements and return them in an array.

In case it helps anyone in the future, I added the following functions to my bst.js:

/**
 * Returns the leftmost n element(s) in the tree
 * @param {Integer} n The number of elements to return from the beginning of the tree
 */
BinarySearchTree.prototype.getFirst = function (n, list) {
  var tmp = [];
  if (!n) n=1; //Default to 1 element
  if (!list) list=[]; //Default list to an empty array so we can concat it

  if (this.left) { //Does it have a left leg?
    tmp = this.left.getFirst(n,list);
    if (tmp.length <= n) { //Make sure we're not already over the n limit
      list = tmp;
    }
  }

  if (list.length < n) { //Make sure we're not already over the n limit
    list.push(this.data);
  }

  if (this.right && list.length < n) { //Does it have a right leg, and do we need to walk down it?
    tmp = this.right.getFirst(n,list);
    if (tmp.length <= n) { //Make sure we're not already over the n limit
      list = tmp;
    }
  }
  return list;
}

/**
 * Returns the rightmost element(s) in the tree
 * @param {Integer} n The number of elements to return from the end of the tree
 */
BinarySearchTree.prototype.getLast = function (n, list) {
  var tmp = [];
  if (!n) n=1; //Default to 1 element
  if (!list) list=[]; //Default list to an empty array so we can concat it

  if (this.right) { //Does this have a right leg?
    tmp = this.right.getLast(n,list);
    if (tmp.length <= n) { //Make sure we're not already over the n limit
      list = tmp;
    }
  }

  if (list.length < n) { //Make sure we're not already over the n limit
    list.push(this.data);
  }

  if (this.left && list.length < n) { //Does this have a left leg, and do we need to walk down it?
    tmp = this.left.getLast(n,list);
    if (tmp.length <= n) { //Make sure we're not already over the n limit
      list = tmp;
    }
  }
  return list;
}

Then, in order to use them in the AVLTree, I added 'getFirst', 'getLast' to the array on line 447 (the line toward the end of the file that says "Other functions we want to use on an AVLTree as if it were the internal _AVLTree"

Again, thanks for this great module! ๐Ÿ‘

Deleting a zero (or any falsible) value deletes the entire key

POC:

var AVLTree = require('binary-search-tree').AVLTree

var k = new AVLTree();

k.insert(10, 0);
k.insert(10, 1);
k.delete(10, 0);
console.log(k.search(10));//returns an empty array

Change:

  // Delete only a value (no tree modification)
  if (currentNode.data.length > 1 && value) {

To:

  // Delete only a value (no tree modification)
  if (currentNode.data.length > 1 && arguments.length > 1) {

Move underscore from "dependencies" to "devDependencies".

According to your package.json, this package has a dependency on underscore ~1.4.4, but looking through your lib/ directory, the only file that require()'s it is avltree.js, but I don't see it used in there.

It looks like it is used in your test directory, though, so I think you still need it in "devDependencies" (and would then have to remove _ = require('underscore') from avltree.js).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.