tlhunter-sorted-set
A JavaScript implementation of Redis' Sorted Sets. Keeps a collection of "members" in order based on their score. Uses skip lists under the hood, like Redis does.
This is a fork of the brilliant but abandoned redis-sorted-map package by Akseli Palén which was itself a fork of the brilliant but abandoned sorted-map package by Eli Skeggs.
Image: The skip list data structure allows search, insert, and removal in O(log(n)) time in average.
Install
$ npm install tlhunter-sorted-set
Test
Run any of the following:
$ npm test
Note: remember to npm install
!
API
The API mostly follows Redis' Sorted Set Commands, with a few additional methods such as .has(member)
.
Members can be strings, symbols, objects, or really any primitive value.
const SortedSet = require('tlhunter-sorted-set');
const z = new SortedSet();
z.add('Terminator', 8.0);
z.add('District 9', 8.0);
z.add('Ex Machina', 0.7);
z.add('Ex Machina', 7.7);
z.set('The Matrix', 8.7);
z.has('Terminator');
z.has('Blade Runner');
z.score('Ex Machina');
z.score('Blade Runner');
z.get('The Matrix');
z.rem('Ex Machina');
z.rem('Ex Machina');
z.del('Ex Machina');
z.rangeByScore(7, 8);
z.rangeByScore(8);
z.rangeByScore(8, null, { withScores: true });
z.count(7, 8);
z.rank('Ex Machina');
z.rank('Terminator');
z.rank('Blade Runner');
z.range(0, 2);
z.range(0, 2, { withScores: true });
z.range(-1);
z.slice(0, 3);
z.card();
z.length
Intersection
const a = new SortedSet(), b = new SortedSet();
a.add('5a600e10', 16);
a.add('5a600e12', 10);
a.add('5a600e14', 9);
a.add('5a600e15', 14);
a.add('5a600e17', 20);
a.add('5a600e18', 13);
a.add('5a600e19', 15);
a.add('5a600e1a', 19);
a.add('5a600e1b', 7);
a.add('5a600e1c', 13);
a.add('5a600e1e', 10);
b.add('5a600e10', 0);
b.add('5a600e11', 15);
b.add('5a600e13', 5);
b.add('5a600e14', 3);
b.add('5a600e15', 14);
b.add('5a600e17', 12);
b.add('5a600e19', 12);
b.add('5a600e1b', 16);
b.add('5a600e1c', 12);
b.add('5a600e1d', 17);
b.add('5a600e1f', 3);
SortedSet.intersect(a, b);
SortedSet.intersect(b, a);
a.intersect(b);
const c = new SortedSet();
c.add('5a600e10', 7);
c.add('5a600e12', 20);
c.add('5a600e13', 9);
c.add('5a600e14', 19);
c.add('5a600e16', 19);
c.add('5a600e17', 1);
c.add('5a600e18', 18);
c.add('5a600e1a', 6);
c.add('5a600e1c', 15);
c.add('5a600e1f', 4);
SortedSet.intersect(c, a, b);
Unique
You can enable unique values with the unique option, which causes set
to throw an error if the value provided already belongs to a different key.
const z = new SortedSet({unique: true});
z.add('5a600e10', 16);
z.add('5a600e11', 6);
z.add('5a600e12', 17);
z.add('5a600e13', 11);
z.add('5a600e14', 14);
z.add('5a600e15', 19);
z.add('5a600e16', 3);
z.add('5a600e17', 12);
z.add('5a600e18', 10);
z.add('5a600e19', 11);
z.add('5a600e14', 14);
Licence
MIT