ordered-set
ordered-set
is a performant ES6 Set subclass that allows control
over iteration order.
Simply provide the set with the ordering function to use
and it will
do the rest.
const OrderedSet = let orderedSet = orderedSetorderedSetorderedSetfor let setItem of orderedSet // iterates in order defined by mySortingFunction
Installation
npm install ordered-set
Required ES6 Features
Although the code is compiled and published as ES5, there are some ES6 standard library features required:
- Symbols
- Set
How to get ES6 features
Install es6-shim or 6to5. traceur also works well. Unfortunately, did not have luck using the more lightweight & modular es6-set & es6-symbol.
You'll need to install an ES6 polyfill yourself, such as those listed above. There is not one included with the package on purpose – this may seem like malpractice and I normally would advise against any kind of implicit dependencies but after battling with these issues across multiple projects I've concluded npm currently has no suitable workflow for anything that mutates the global environment i.e. must be a singleton.
I feel this should be best-practice for language polyfills – by omitting a transpiler you're free to use this with whatever transpiler you're already using.
This lib could be easily reworked to not require these ES6 features but the intended audience is people already compiling to ES6, or those interested in doing so.
Usage
const OrderedSet = // Default sortFunction is numeric, ascending:// (a, b) => a - blet orderedSet = orderedSetorderedSetorderedSet orderedSet// orderedSet default sortFunction 1// orderedSet default sortFunction 2// orderedSet default sortFunction 3
.use(fn)
Replace sorting function with orderedSet // e.g. reversed ordering orderedSet// orderedSet custom sortFunction 3// orderedSet custom sortFunction 2// orderedSet custom sortFunction 1
Regular ES6 Set for comparison
let regularSet = regularSetregularSetregularSet
ES6 Sets iterate in insertion order
regularSet// regular set 2// regular set 1// regular set 3
OrderedSet Supports all regular ES6 Set operations & usage
orderedSet = 321orderedSetconsole // set.size 4orderedSetconsole // set.size 3
License
MIT