Scontainers is a container/collection/iterator library for JavaScript, comfortable to use, performant and versatile.
Scontainers offers functional-style operations like forEach
, map
, filter
, reduce
etc, similarly to lodash and underscore, but it...
- can be used with a nicer, more natural syntax. Scontainers is built using
straits
: its functions can be called using the straits syntax, as free functions or as member symbols. - is blazing fast. Even million of times faster than the alternatives: as fast as writing a hand-tuned for loop.
- it's more powerful and versatile: it works lazily and can be used on any kind of collection (objects, arrays of any kind, ES6
Set
andMap
, lazy structures likeRange
and so on). Iterators and collection's data can also be collected into any container of your choice.
This example uses the straits syntax. Refer to the straits documentation to see how to use it with free functions or member symbols.
The following example transforms a string into the binary representation of its ASCII characters, then back to a string:
import scontainers from 'scontainers';
use traits * from scontainers; // enabling the .* operator
const encoded =
"★Hey!★" // "★Hey!★"
.*map( char=>char.charCodeAt(0) ) // 9733, 72, 101, 121, 33, 9733
.*filter( num=>num<128 ) // 72, 101, 121, 33
.*map( num=>num.toString(2) ) // "1001000", "1100101", "1111001", "100001"
.*map( str=>str.padStart(8, '0') ) // "01001000", "01100101", "01111001", "00100001"
.*join( ' ' ); // "01001000 01100101 01111001 00100001"
const decoded =
encoded.split(' ') // "01001000", "01100101", "01111001", "00100001"
.*map( bin=>parseInt(bin, 2) ) // 72, 101, 121, 33
.*map( num=>String.fromCharCode(num) ) // "H", "e", "y", "!"
.*join(); // "Hey!"
Scontainers introduces a set of traits (i.e. symbol
s to be used as property keys) used to express the capabilities relevant to collections and containers:
- containers are collections that store each of their elements in memory. An example could be
[1,2,3]
, - collections are objects that can logically contain zero or more elements. Some examples are
[1,2,3].*map(n=>n*n)
ornew Range(2, 7)
; of course[1,2,3]
is a collection as well.
For instance, if an object has the symbol
nth
, then we know that such object is a collection whose elements can be enumerated, and the n
th element of the collection can be accessed as object.nth(n)
.
Scontainers currently supports collections that can be accessed the following ways:
- using a key, that can be of any kind. An example of this is
Map
. - using an index: an integer between 0 and the size of the collection. Unless a different key access function is provided, the index can also be used as a key to access elements in the collection using the previous mechanism.
Elements of collections are represented as a KVN object, rather than a key-value pair.
Scontainers defines a set of "core traits" that define some core properties of containers and collections and ways to access to these: the size of the collection, a way to access the n
th element, the way to access an element with a given key
, a way to tell whether an element belongs to the collection, ways to modify the collection, ways to iterate through the collection's elements etc. These core traits should be implemented only for those types or objects that can implement them natively and efficiently: the len
trait to compute the size of a collection shouldn't be implemented by traversing the whole collection.
Other traits can be derived from existing ones, and these are called "derived traits". For instance, if all the elements of a collection can be accessed with indices ranging from 0
to len()
, then the forEach
and reverse
operations can be automatically derived; if the len
is available, or if it's possible to iterate through the whole collection, then count
can be derived. These traits can of course be explicitly implemented as well, in case a smarter or more efficient implementation is available.
Scontainers implements the Symbol.iterator
trait compatible to the iterable protocol, but it also defines other iterators: kvIterator
and kvReorderedIterator
.
kvIterator
is used the same way as iterator
, but the objects next()
returns is either a KVN or undefined
.
kvReorderedIterator
is able to handle synchronous iteration on reordered collections, like [3,1,2].*sort()
.
Some of the traits defined by scontainers can be used to derive new collections from existing ones.
For instance map
: it operates on a collection and returns a new collection with the same size; for each element <index,key,value>
in the original collection, the resulting one has an element <index,key,f(value,key,index)>
.
Another example is filter
: it returns a collection like the original one stripped of the elements for which f(value,key,index)
returns false
.
Unless otherwise specified, transformations are lazy: they return a wrapper around the original collection, without processing or allocating any new data.
Let's look at some examples of some types and the traits they can implement...
[1,2,3]
's size is known (it's stored in its.length
property) and its elements are enumerated and can be accessed using an index:len
andnth
are both implemented (forArray.prototype
). Most scontainers operations are automatically derived forArray
s and are available on[1,2,3]
. Theget
trait that allows accessing items using a key is also implemented forArray.prototype
: it behaves likenth
(but it doesn't fail if the key is not a number or greater thanlen
).[1,2,3].*map(n=>n*n)
implements the same traits as itslen
andnth
traits wrap the ones of[1,2,3]
.[1,2,3].*filter(n=>n%2)
cannot implement neitherlen
nornth
: the size of this collection is unknown and we can't tell which element is then
th, unless we test every element starting from the first one. This collection can still be iterated through though, so thecount
,forEach
,map
traits, as well as many others, are still available.[1,2,3].*filter(n=>n%2).map(n=>n*n)
,[1,2,3].*map(n=>n*n).*filter(n=>n%2)
and[1,2,3].*map(n=>n*n).filter(n=>n%2).*filter(n=>n%3)
implement the same traits as[1,2,3].*filter(n=>n%2)
: no further properties are lost by these operations, nor gained.
In order to massively speed up scontainers operations, the code for some traits can be generated at runtime.
Take the following example:
const c = [1,2,3];
const rc = c.*reverse();
const mrc = rc.*map( fn );
console.log( mrc.*nth(n) );
mrc.*nth(n)
would call rc.*nth(n)
which would call c.*nth(m)
(with m=c.*len()-n
) which would return c[m]
. These nested calls are quite slow with the existing JavaScript engines. If you were to manually implement mrc.*nth(n)
, the efficient version you would write would simply be c[c.*len()-n]
.
Of course it's not possible to manually implement every operation for every collection and all their combination of transformations (which are infinite). What scontainers do is using "trait generators": some traits that expose all the necessary information to dynamically generate efficient code.
The code generation efforts are still ongoing: the generated code can be further optimized and code is not yet generated for many traits, but for many common operations scontainers is already achieving astonishing results.
Scontainers introduces Range
: a virtual collection made of all the integers in a certain range.
new Range( [[begin,] end] )
Range
has the members properties begin
and end
and the method len()
.
new Range(); // Range from 0 to Infinity
new Range(10); // Range from 0 to 10
new Range(20, 55); // Range from 20 to 55
const assert = require('assert');
const rng = new Range();
assert.eq( rng.begin, 0 );
assert.eq( rng.end, Infinity );
assert.eq( rng.len(), Infinity );
A KVN is an object used to describe an element of a collection.
A KVN has up to three fields:
key
: the key of an elementvalue
: the element's valuen
: the element's index
This concept is similar to a key-value pair, but is also able to carry information on the element's enumerable order.
Let's see a couple of examples: the KVN of the only element of new Map([[2,"hey"]])
is {key:2, value:"hey"}
. The KVN of the only element of ["yo"]
is {key:0, n:0, value:"yo"}
. The KVN of the only element of ["a", "b"].*slice(1)
is {key:1, n:0, value:"b"}
.
Most transformations try to preserve the original key of an element, while the index, if available, is always between 0
and .*len()-1
.
Scontainers' native iterators (see the kvIterator
and kvReorderedIterator
traits) as well as functions meant to search for elements (e.g. first
, random
) return a KVN if an element is found or undefined
if no element was found or if the end of the iterator has been reached.
The scontainers traits are implemented for the following types:
Array
Map
Set
String
: a collection of all the UTF-16 characters in the string.
Object
doesn't implement the scontainers traits directly, but the traits are implemented for the own properties and the enumerable properties of an object:
object.*ownProperties()
: a collection of all the own properties ofobject
.object.*properties()
: a collection of all the enumerable properties ofobject
.
Scontainers defines the following traits:
ContainerType.*from( collection )
, returns a new instance of a container of typeContainerType
containing the elements ofcollection
.
The following operations must be asymptotically fast; preferably O(1).
-
collection.*len()
, returns the amount of elements ofcollection
. -
collection.*nth( n )
, returns the value of then
th element ofcollection
. -
collection.*nthKVN( n )
, returns the KVN (an object withkey
,value
andn
fields) for then
th element ofcollection
. -
collection.*get( key )
, returns the value of the element with keykey
ofcollection
. -
collection.*getKVN( key )
, returns the KVN of the element with keykey
ofcollection
. -
collection.*has( value )
, tells whethervalue
is an element ofcollection
. -
collection.*hasKey( key )
, tells whethercollection
has an element with keykey
. -
collection.*nToKey( n )
, returns the key of then
th element ofcollection
. -
collection.*keyToN( key )
, returns the index of the element ofcollection
with keykey
. -
collection.*add( value )
, addsvalue
to the collection. -
collection.*setNth( n, value )
, setsvalue
as then
th element ofcollection
. -
collection.*set( key, value )
, setsvalue
as the element with keykey
incollection
.
Consumers:
-
collection.*forEach( fn )
, callsfn(value, key, n)
for every item incollection
-
collection.*whileEach( fn )
, callsfn(value, key, n)
for every item incollection
, it stops whenfn(value, key, n)
returns false. -
collection.*untilEach( fn )
, callsfn(value, key, n)
for every item incollection
, it stops whenfn(value, key, n)
returns true. -
collection.*every( fn )
, returns true iffn(value, key, n)
returned true for every element ofcollection
, false otherwise. -
collection.*some( fn )
, returns true iffn(value, key, n)
returned true for at least one element ofcollection
, false otherwise. -
collection.*count()
, returns the amount of elements ofcollection
. It's semantically identical tocollection.*len()
, but could be way slower (it might be implemented by traversing the whole collection, if a better way is not available). -
collection.*isEmpty()
, true ifcollection
has no elements, false othrwise. -
collection.*only()
, returns the only item incollection
. Ifcollection
has more than one item, it throws an exception. -
collection.*one()
, returns one item incollection
, whatever is faster to retrieve. -
collection.*first()
, returns the first item incollection
. Asymptotically fast. -
collection.*last()
, returns the last item incollection
. Asymptotically fast. -
collection.*random()
, returns a random item incollection
. Asymptotically fast. -
collection.*swapNs( n1, n2 )
, swaps the elements with indicesn1
andn2
incollection
. -
collection.*swapKeys( k1, k2 )
, swaps the elements with keysk1
andk2
incollection
. -
collection.*reduce( fn, initialValue )
, applies a function against an accumulator and each element in the collection (from left to right) to reduce it to a single value. Semantically similar toArray.prototype.reduce
. -
collection.*reduceFirst( fn )
, likecollection.*reduce()
, except that it uses the first element ofcollection
as initial value and it doesn't iterate on it. -
collection.*sum()
, returns the sum of all the numbers incollection
. -
collection.*avg()
, returns the average of the numbers incollection
. -
collection.*min()
, returns the smallest number incollection
. -
collection.*max()
, returns the largest number incollection
. -
collection.*join( sep='' )
, returns a string obtained joining all the string incollection
together, withsep
in between each couple of strings.
Decorators:
-
collection.*iterator()
, an alias forSymbol.Iterator
-
collection.*kvIterator()
, returns a KVN Iterator: eithernull
, ifcollection
was empty, or an object with three propertieskey
,value
andn
and a methodnext()
. The properties represent an element ofcollection
we're iterating on, whilenext()
returnsnull
, if the end of the collection has been reached, or an element like itself representing the following element in the collection. -
collection.*kvReorderedIterator()
, returns a KVN Reordered Iterator: an object that has a propertystate
and two callbacksonNextFn
andonEndFn
. It has the methodsproceed()
,resume()
andstop()
to control the state of the KVN Reordered Iterator andonNext(cb)
andonEnd(cb)
to register callback. A KVN Reordered Iterator is a more generic way to iterate on collections, which supports collections that are not in order (e.g. the result ofcollection.*sort()
orcollection.*groupBy()
), although it's slower. -
collection.*collect(ContainerType)
-
collection.*collectInto(ContainerType)
-
collection.*reverse()
, returns a collection with the same elements ascollection
, but in reversed order. -
collection.*keys()
, returns a collection whoseiterator()
trait iterates on the keys ofcollection
. -
collection.*values()
, returns a collection whoseiterator()
trait iterates on the values ofcollection
. -
collection.*entries()
, returns a collection whoseiterator()
trait iterates on the entries ofcollection
(arrays whose first element is the key and the second the value). -
collection.*enumerate()
, returns a collection identical tocollection
, but whose indices are numerated continuously when iterating on it. -
collection.*filter(fn)
, returns a collection containing the same elements ascollection
excluding thosefn(value, key, n)
returns false for. -
collection.*uniq(eq)
, returns a collection containing the same elements ascollection
excluding those that follow the same value as themselves. -
collection.*slice(begin, end)
, returns a slice ofcollection
, between the element with indexbegin
and that with indexend
. -
collection.*chunk(n)
, returns a collection made of slices ofcollection
, each containingn
elements. -
collection.*map(fn)
, returns a collection derived fromcollection
, whose values are the result offn(value, key, index)
. -
collection.*mapKey(fn)
, returns a collection derived fromcollection
, whose keys are the result offn(value, key, index)
. -
collection.*cache(ContainerType=Map)
, returns a collection that caches the values ofcollection
. When directly accessing an element of this container, the element is cached in a container of typeContainerType
and it will be retrieved from there for the following accesses. -
collection.*flatten()
:collection
must be a collection of collections; returns a collection of the element inside the collections insidecollection
. -
collection.*flattenDeep()
, likeflatten()
, but recursive. -
collection.*concat(...collections)
, returns a collection with the element ofcollection
and then the ones of thecollections
. -
collection.*skipWhile(fn)
, returns a collection identical tocollection
excluding all the elementsfn(value, key, n)
returns true for until the first element for which false is returned. -
collection.*takeWhile(fn)
, returns a collection identical tocollection
containing only the elementsfn(value, key, n)
returns true for until the first elements for which false is returned. -
collection.*skip(n)
, returns a collection containing all except the firstn
elements ofcollection
. -
collection.*take(n)
, returns a collection containing the firstn
elements ofcollection
. -
collection.*groupBy(fn)
, returns a collection of collections: each element ofcollection
belongs to the collection with keyfn(value, key, n)
. -
collection.*cow(ContainerType=Map)
, returns a wrapper aroundcollection
which implements the modification traits and allocates a new container of typeContainerType
with all the values ofcollection
the first time it's modified. -
collection.*remap(fn)
, returns a collection whose keys and values are those of the KV returned byfn(value, key, n)
for each element ofcollection
. -
collection.*kvMap(fn)
, returns a collection with an element for each element ofcollection
: the key for each element is a KV with the current key and the current value and the value is the one returned byfn(value, key, n)
. -
collection.*unmap()
:collection
must be a collection of collections; returns a collection with the key and value of the KV of each element ofcollection
. -
collection.*unmapKeys()
:collection
must be a collection whose keys are KV; returns a collection with the key and value of the KV of each key ofcollection
. -
collection.*sort(cmp)
, returns a collection with the same elements ascollection
, sorted according tocmp(kvn1, kvn2)
. -
collection.*shuffle()
, returns a collection with the same elements ascollection
, randomly sorted. -
collection.*permute()
, . -
collection.*groupWhile(fn)
, returns a collection of collections, each containing all the continuous elementsfn(value, key, n)
returned true for. -
collection.*repeat(n=Infinity)
, returns a collection identical tocollectcion
repeatedn
times. -
collection.*assign(...collections)
, return a collection where the elements ofcollections
have been added (overwriting if necessary) to those ofcollection
. -
collection.*defaults(...collections)
, return a collection where the elements ofcollections
have been added to those ofcollection
, without overwriting existing ones.
Scontainers is still in its alpha stage. Some of its traits already work, but some might be broken and a few extremely important features are still missing.
In particular we still need to...
- implement or fix several missing or broken traits,
- implement or fix code generation for many traits,
- expand test coverage,
- make it possible to derive third party traits on existing collections and handle new versions better (see status of straits),
- improve documentation.