gwtw / js-avl-tree

A JavaScript implementation of the AVL tree data structure
MIT License
35 stars 12 forks source link

Readme demo results in errors #12

Open freiit opened 2 years ago

freiit commented 2 years ago

I just wanted to try out the project and copy/pasted the example in the README-file.

var tree = new AvlTree();
           ^

TypeError: AvlTree is not a constructor

Anything I can do to get this up and running?

Tyriar commented 2 years ago

How are you importing it? The readme shows:

var AvlTree = require('@tyriar/avl-tree');

Which would mean you may need to do this for import:

import * as AvlTree from '@tyriar/avl-tree';

You could log/debug AvlTree to see what it is which might also give you your answer.

freiit commented 2 years ago

I copy/pasted the code 1:1 from the README file: see gist and executed it with node dummy.js.

Tyriar commented 2 years ago

Looks like the readme is a little out of date, the following works for me which has a change on the require line and also changes .size() to .size:

// Import npm module
var AvlTree = require('@tyriar/avl-tree').AvlTree;

// Construct AvlTree
var tree = new AvlTree();

// Insert keys
tree.insert(1);
tree.insert(2);
tree.insert(3);
tree.insert(4);
tree.insert(5);
console.log('size: ' + tree.size);
console.log('contains 2: ' + tree.contains(2));
console.log('contains 7: ' + tree.contains(7));
// > size: 5
// > contains 2: true
// > contains 7: false

// Delete a key
tree.delete(2);
console.log('size: ' + tree.size);
console.log('contains 2: ' + tree.contains(2));
// > size: 4
// > contains 2: false

// Construct custom compare AvlTree
tree = new AvlTree(function (a, b) {
  return a.localeCompare(b);
});
tree.insert('a');
tree.insert('A');
tree.insert('b');
tree.insert('B');

// Delete the minimum key
var minKey = tree.findMinimum();
tree.delete(minKey);
console.log('minKey: ' + minKey);
console.log('new minKey: ' + tree.findMinimum());
// > min key: 'a'
// > new min key: 'A'

FYI the module actually uses the TypeScript port at https://github.com/gwtw/ts-avl-tree, so @tyriar/avl-tree points at that repo

freiit commented 2 years ago

Thanks. :-) Shall I make a patch?

Tyriar commented 2 years ago

Sure, but I think the most correct thing to do would be call out this is mainly for education and recommend https://github.com/gwtw/ts-avl-tree instead actual usage