Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

scl

samvv397MIT4.1.1TypeScript support: included

A curated set of essential algorithms and data structures for TypeScript

data, algorithm, data-structure, library, typescript, collection, priority-queue, avl-tree, hash-map, hash-set, dictionary, map, set

readme

Build Status Coverage Status

This is a curated, open-source project of common JavaScript collections with full support for TypeScript. Initially started as a side-project to abstract away some common patterns in other projects, this library continues to grow to become a full standard library of efficient algorithms.

npm i scl

☝️ We could use a helping hand. If you think you're up for it, open an issue.

📖 Go straight to the documentation!

Examples

Using the priority queue to sort some tasks on importance

import { PriorityQueue } from "scl"

interface Task {
 priority: number
 description: string
}

const tasks = new PriorityQueue<Task>({
  compare: (a, b) => a.priority < b.priority
})

tasks.add({ description: 'Do the dishes', priority: 5 })
tasks.add({ description: 'Buy food', priority: 1 })
tasks.add({ description: 'Play some games', priority: 52 })
tasks.add({ description: 'Go for a walk', priority: 10 })
tasks.add({ description: 'Program like crazy', priority: 20 })

// Take the most important task from the queue
const buyFood = tasks.pop();

// See what the next task looks like without removing it
const doTheDishes = tasks.peek()

console.log('I should do the remaining tasks in the following order:');
for (const task of tasks) {
  console.log(`- ${task.description}`);
}

This will output the following text:

I should do the remaining tasks in the following order:
- Do the dishes
- Go for a walk
- Program like crazy
- Play some games

Sorting and querying a list of people based on their age

import { TreeIndex } from "scl"

interface Person {
  name: string;
  email: string;
  age: number;
}

const people = new TreeIndex<Person, string>([
  {
    name: 'Bob',
    email: 'thebobman@gmail.com',
    age: 45,
  },
  {
    name: 'Fred',
    email: 'fred@outlook.com',
    age: 33,
  },
  {
    name: 'Lisa',
    email: 'lisa.turner@gmail.com',
    age: 37,
  }
]);

// Lisa is the oldest person who is at the very most 40 years old.
const lisa = people.getGreatestLowerBound(40);

// Bob is the youngest person older than Lisa
const bob = lisa.next();

// No one is older than Bob
assert(bob.next() === null);

Storing many different translations in the same dictionary

import { TreeMultiDict } from "scl"

const d = new TreeMultiDict<number, string>([
  [1, 'Ein'],
  [2, 'dos'],
  [1, 'uno'],
  [2, 'Zwei'],
  [2, 'duo'],
])

const oneInDifferentLanguages = [...d.getValues(1)];

for (const word of oneInDifferentLanguages) {
  console.log(`The number 1 can be translated as '${word}'`);
}

const [added, threeCursor] = d.emplace(3, 'tres')

if (d.hasKey(3)) {
  console.log(`The dictionary now has 3 in its keys.`);
} else {
  console.log(`The dictionary does not contain 3.`);
}

console.log(`The dictionary now has ${d.size} elements.`)

d.deleteAt(threeCursor)

The output of the above program:

The number 1 can be translated as as 'uno'
The number 1 can be translated as as 'Ein'
The dictionary now has 3 in its keys.
The dictionary now has 6 elements.

Usage

The sources in this library target a relatively new ECMAScript version, so that you are able to choose how much backwards-compatible the generated JavaScript should be. You are expected to use this library with a bundler such as Webpack or Rollup. Recent versions of NodeJS should also work without any bundler.

There is experimental support for tree shaking, which will result in much smaller JavaScript bundles. If you encounter an issue with this, please take your time to report it.

Documentation

All collections are documented using TypeDoc, and the latest documentation is available here.

If you've found a mistake in the documentation or something is not quite clear, don't hesitate to open an issue.

Support

Found an issue? A certain mistake? Need a certain kind of collection? File an issue or send me a pull request.

Credits

Thanks to Wolfgang De Meuter's introductory course to algorithms and data structures for teaching many of the concepts that are used in this library.

Many thanks to @w8r for providing a reference implementation of the AVL-tree data structure.

License

The MIT License

changelog

Change Log

This document keeps track of any changes made to the software.

v4.1.0

  • Fix critical bug occurring because main index.js is not being found due to missing 'main' field in package.json
  • Updated the examples in the README.md
  • Enabled ESLint on the entire code base

v4.0.0

  • Generated JavaScript now has all comments removed
  • Introduced a Red/Black tree as an alternative to the AVL tree
  • TreeDict and TreeMultiDict now use Red/Black trees instead of AVL trees
  • Extracted common logic in AVLTreeIndex and RBTreeIndex into BSTreeIndex
  • Renamed upperKey() to getLeastUpperBound() and lowerKey() to getGreatestLowerBound()
  • Refactored some internal variables to be more consistent and readable
  • Renamed CollectionCursor to simply Cursor and CollectionRange to simply Range
  • Removed the TreeManyDict and HashManyDict implementations
  • Added a ResolveAction and make the indices able to adjust behaviour based on this value
  • Dict.getValue() now returns undefined instead of null if the key was not found
  • Made DictLike.getValue() not throw an error if a key is not found
  • Fixed a bug in the AVL tree rebalancing algorithm
  • Added more tests

v3.1.0

  • Rename IndexedCollection to just Index
  • Make AVLTreeIndex available to end-users
  • Do some refactoring on internal properties

v3.0.0

  • Moved files around to be much easier to maintain and easier for newcomers to get a grip on
  • Added experimental support for tree shaking
  • Fixed some issues with missing/wrong documentation
  • The collections now should be imported using the top-level index.ts file
  • Removed dependency on xxhash and added a custom hashing function.
  • Added ability to quickly define hashable/comparable classes with special tag symbols
  • Fixed some bugs such as an infinite loop in SingleLinkedList
  • Hash functions now return a string instead of a number
  • Renamed some utility functions, such as lesser to lessThan
  • Fixed the lessThan comparison function
  • Added more documentation

v2.0.0

  • Renamed the Container concept to Collection
  • Multi-index collection composition is temporarily removed
  • Structure is now IndexedCollection
  • A View is now a CollectionRange
  • deleteAll and delete are now required methods of Collection
  • Added Collection.toRange() as a replacement for Collection.begin() and Collection.end()
  • Added and implemented Queuelike.peek() for all relevant collections
  • Renamed Queuelike.dequeue() to Queuelike.pop()
  • Collection.size is now a property to match built-in collections
  • delete and deleteAll now return information about the deletion that took place
  • Removed Vector, MinHeap and MaxHeap as implementable interfaces
  • Added View.size property
  • Constructors can now take an iterator and an options object where applicable
  • Created a new build system
  • Introduced strict mode and fixed all TypeScript errors
  • Fixed multiple bugs and API inconsistencies
  • Updated all dependencies to migitate security risks
  • Fixed all TypeScript errors

v1.0.2

  • Added more tests
  • Fixed a few bugs
  • Moved indices to separate files
  • Updated the lockfiles

v1.0.1

  • Fixed critical bug in reflect-types dependency

v1.0.0

  • Fixed JavaScript not being pushed to registry

v0.9.1

  • Some bugfixes in container implementations

v0.9.0

  • Added a container type registration system
  • Made container composition work with some examples
  • Streamlined AVL and hash implementations
  • Switched to XXHash for much better hashing results
  • Removed UniqueContainer and MultiContainer interfaces
  • Renamed UnorderedContainer to Sequence and OrderedContainer to Structure

v0.8.1

  • Updated the README

v0.8.0

  • Rename UnorderedContainer to Sequence in interfaces
  • add() is now a required method of Container interface
  • Made iterator, next() and prev() optional in Cursor interface
  • Added tree-based dictionaries
  • Optimised min/max-search in AVL tree
  • Made order undefined for dictionaries
  • Removed sequenced list from hash implementation
  • Added basic support for container composition

v0.7.2

  • Added variants of the hash-based dictionaries
  • Standard hash-based dictionary now replaces keys

v0.7.1

  • Many fixes in hash implementation

v0.7.0

  • Removed dangling ES6 wrappers
  • Added a hash set and hash dictionary
  • Updated container API to include deleteAt()
  • Made all inserters return a cursor in container API
  • Updated list implementations to return cursors upon insertion
  • Added a tree set and tree dictionary
  • Removed unclear grid data structures

v0.6.0

  • Introduced new cursor API for iterating through container elements
  • Updated vector, single-linked list and double-linked list to conform to new API
  • Added an AVL-tree implementation
  • Temporarily removed support for ES6 wrappers

v0.5.1

  • Fixed missing compiled files in published package

v0.5.0

  • Created a change log
  • Fixed missing stack implementation
  • Fixed deleteAll in list implementations
  • Added a queue implementation

v0.4.1

  • Added a double-linked list implementation
  • Single-linked list insert is now always O(1)
  • Size querying of single-linked lists is no longer O(n)