seqeuence

Gen­eric lib­rary for ad­vanced util­iz­a­tion of es6 iter­at­ors.

map, fold and so on...

se­quence.js func­tions are fully lazy and work with any­thing im­ple­ment­ing the iter­ator pro­tocol; in ad­di­tion, all func­tions also sup­port treat­ing plain ob­jects as se­quences!

The ad­vant­age of lazy im­ple­ment­a­tions is that these func­tions work ef­fi­ciently with very long or even in­fin­ite se­quences; as­sum­ing the fol­low­ing ex­ample is given a se­quence with ten bil­lion ele­ments, it would still start print­ing it's out­put im­me­di­ately and would not re­quire cre­at­ing an­other bil­lion ele­ment ar­ray as Ar­ray.map would do. In prac­tice the x*2 would be cal­cu­lated im­me­di­ately be­fore the res­ult is prin­ted.

each(map(se­quence, (x) => x*2), con­sole.log)

A dis­ad­vant­age of lazy­ness is that side ef­fects (e.g. a con­sole.log in­side a map()) are not ex­ecuted, be­fore the res­ult­ing se­quence is ac­tu­ally be­ing con­sumed by a for loop or each() or fold() or sim­ilar func­tions… So if you need to per­form side ef­fects, re­mem­ber to use one of these in­stead of lazy func­tions like map();

se­quence.js func­tions also sup­port passing func­tions as the last ar­gu­ment:

each(seq, (elm) => {
  doSomething(elm);
  con­sole.log(elm);
});

is much more read­able then the ex­ample be­low; es­pe­cially when you are us­ing mul­tiple nes­ted each/​map/​fold calls and the func­tion bod­ies grow long!

each((elm) => {
  doSomething(elm);
  con­sole.log(elm);
}, seq);

Some of the util­it­ies in here can mostly be im­ple­men­ted with stand­ard js6. The em­phasis here is on mostly, since se­quence.js func­tions are de­signed to have fewer edge cases that clas­sical es6 pendants and there­for make for a smoother cod­ing ex­per­i­ence.

Ex­amples:

It­er­a­tion

> for (const v of {foo: 42, bar: 23}) con­sole.log(v);
TypeEr­ror: {(in­ter­me­di­ate value)(in­ter­me­di­ate value)} is not it­er­able

Does not work be­cause plain ob­jects do not im­ple­ment the iter­ator pro­tocol.

Re­place With

> each([1,2,3,4], con­sole.log);
1
2
3
4

or

> each({foo: 42}, v => con­sole.log(v));
[ 'foo', 42 ]

or the fol­low­ing if the full power of a for loop is really re­quired..

for (const v of iter({foo: 42})) con­sole.log(v);
[ 'foo', 42 ]

Ar­ray.forEach

> [1,2,3,4].forEach(con­sole.log)
1 0 [ 1, 2, 3, 4 ]
2 1 [ 1, 2, 3, 4 ]
3 2 [ 1, 2, 3, 4 ]
4 3 [ 1, 2, 3, 4 ]
```

Un­ex­pec­tedly yields a lot of out­put; that is be­cause forEach also passes
the in­dex in the ar­ray as well as the `this­Ar­gu­ment`.
This be­ha­viour is of­ten un­ex­pec­ted and forces us to define an in­ter­me­di­ate
func­tion.

## Re­place With

```
> each([1,2,3,4], con­sole.log);
1
2
3
4
```

If the in­dex is really needed, `enu­mer­ate()` may be used:

```
each(enu­mer­ate([42, 23]), con­sole.log)
[ 0, 42 ]
[ 1, 23 ]
```

As a sid­e­note this also ef­fort­lessly fits the concept of a key/​value
con­tainer; the out­put of `enu­mer­ate([42, 23])` could eas­ily passed
into `new Map(...)`;

The full be­ha­viour of for each
Source:

Interfaces

Sequence
Into

Members

(inner, constant) extend

Source:

Gen­er­ate a se­quence by re­peatedly call­ing the same func­tion on the pre­vi­ous value.

This is of­ten used in con­junc­tion with tak­eDef or take­While to gen­er­ate a non-in­fin­ite se­quence.

// Gen­er­ate an in­fin­ite list of all pos­it­ive in­tegers
ex­tend(0, x => x+1);
// Gen­er­ate the range of in­tegers [first; last[
const range = (first, last) =>
  takeUntilVal(ex­tend(first, x => x+1), last);

(inner, constant) extend1

Source:

Like ex­tend(), but the res­ult­ing se­quence does not con­tain the ini­tial ele­ment.

(inner, constant) flattenTree

Source:

Flat­ten trees of any type into a se­quence.

The given func­tion ba­sic­ally has three jobs:

  1. De­cide whether a given value in a tree is a node or a leaf (or both)
  2. Con­vert nodes into se­quences so we can eas­ily re­curse into them
  3. Ex­tract val­ues from leaves

If the given func­tion does it's job cor­rectly, visit will yield a se­quence with all the val­ues from the tree.

The func­tion must re­turn a se­quence of val­ues! It is given the cur­rent node as well as a call­back that that takes a list of child nodes and flat­tens the given sub­nodes.

Use the fol­low­ing re­turn val­ues:

flat­ten­Tree((node, re­curse) => {
  if (isEmptyLeaf()) {
    re­turn [];

  } else if (is­Leaf(node)) {
    re­turn [node.value];

  } else if (is­Mul­tiLeaf(node)) {
    re­turn node.val­ues;

  } else if (is­Node(node)) {
    re­turn re­curse(node.child­Nodes);

  } else if (is­LeafAnd­Node(node)) {
    re­turn con­cat([node.value], re­curse(node.child­Nodes));
  }
 }
});

(inner, constant) nth

Source:

Ex­tract the nth ele­ment from the se­quence

(inner, constant) each

Source:

It­er­ate over se­quences: Ap­ply the give func­tion to every ele­ment in the se­quence

(inner, constant) join

Source:

Con­vert each ele­ment from a se­quence into a string and join them with the given sep­ar­ator.

(inner, constant) into

Source:

Con­vert val­ues into a given type us­ing the Into trait. Note that this has in­verse para­met­ers com­pared to the trait (se­quence first, type second) for cur­ry­ing pur­poses.

(inner, constant) foldl

Source:

Com­bine all the val­ues from a se­quence into one value.

This func­tion is also of­ten called re­duce, be­cause it re­duces mul­tiple val­ues into a single value.

Here are some com­mon use cases of the foldl func­tion:

const all = (seq) => foldl(seq, true, (a, b) => a && b);
const any = (seq) => foldl(seq, false, (a, b) => a || b);
const sum = (seq) => foldl(seq, 0, (a, b) => a + b);
const product = (seq) => foldl(seq, 1, (a, b) => a * b);

No­tice the pat­tern: We ba­sic­ally take an op­er­ator and ap­ply it un­til the se­quence is empty: sum([1,2,3,4]) is pretty much equi­val­ent to 1 + 2 + 3 + 4.

(If you want to get very math­em­at­ical here...no­tice how we ba­sic­ally have an op­er­a­tion and then just take the op­er­a­tion's neut­ral ele­ment as the ini­tial value?)

(inner, constant) foldr

Source:

Like foldl, but right-to-left

(inner, constant) map

Source:

Lazily trans­form all the val­ues in a se­quence.

into(map([1,2,3,4], n => n*2), Ar­ray) # [2,4,6,8]

(inner, constant) filter

Source:

Re­move val­ues from the se­quence based on the given con­di­tion.

fil­ter(range(0,10), x => x%2 == 0) // [2,4,6,8]

(inner, constant) reject

Source:

Op­pos­ite of fil­ter: Re­moves val­ues from the se­quence if the func­tion re­turns true.

(inner, constant) trySkip

Source:

Like skip, but re­turns an ex­hausted iter­ator if the se­quence con­tains less than no ele­ments in­stead of throw­ing Iter­atorEn­ded.

(inner, constant) skip

Source:

Skip ele­ments in a se­quence. Throws Iter­atorEn­ded if the se­quence con­tains less than no ele­ments.

(inner, constant) skipWhile

Source:

Skips ele­ments in the given se­quences un­til one is found for which the pre­dic­ate is false.

(inner, constant) tryTake

Source:

Yields an iter­ator of the first no ele­ments in the given se­quence; the res­ult­ing iter­ator may con­tain less then no ele­ments if the in­put se­quence was shorter than no ele­ments.

(inner, constant) take

Source:

Ver­sion of tryTake that will throw Iter­atorEn­ded if the given it­er­able is too short.

(inner, constant) takeWhile

Source:

Cut off the se­quence at the first point where the given con­di­tion is no longer met.

list(take­While([1,2,3,4,5,6...], x => x < 4)) yields [1,2,3]

(inner, constant) takeUntilVal

Source:

Cut of the se­quence at the point where the given value is first en­countered.

(inner, constant) prepend

Source:

Given a se­quence and a value, pre­pend the value to the se­quence, yield­ing a new iter­ator.

(inner, constant) append

Source:

Given a se­quence and a value, ap­pend the value to the se­quence, yield­ing a new iter­ator.

(inner, constant) mapSort

Source:

Sort a se­quence. The given func­tion must turn map each para­meter to a string or num­ber. Ob­jects will be sor­ted based on those num­bers.A If the given para­met­ers are already num­bers/​strings, you may just use iden­tity as the map­ping func­tion.

(inner, constant) zipLeast2

Source:

Curry­able ver­sion of zipLeast

(inner, constant) zip2

Source:

Curry­able ver­sion of zip

(inner, constant) zipLongest

Source:

Zip mul­tiple se­quences. Puts all the first val­ues from se­quences into one sub­list; all the second val­ues, third val­ues and so on... If the se­quences are of dif­fer­ent length, the res­ult­ing iter­ator will have the length of the longest se­quence; the miss­ing val­ues from the shorter se­quences will be sub­sti­tuted with the given fall­back value.

(inner, constant) zipLongest2

Source:

Curry­able ver­sion of zip­Longest

(inner, constant) slidingWindow

Source:

Forms a slid­ing win­dow on the un­der­ly­ing iter­ator.

slid­ing­Win­dow([1,2,3,4,5], 3) yields [[1,2,3], [2,3,4], [3,4,5]]

Will throw Iter­atorEn­ded if the se­quence is shorter than the given win­dow.

(inner, constant) trySlidingWindow

Source:

Like slid­ing­Win­dow, but re­turns an empty se­quence if the given se­quence is too short.

(inner, constant) lookahead

Source:

Al­most like trySlid­ing­Win­dow, but makes sure that every ele­ment from the se­quence gets it's own subar­ray, even the last ele­ment. The ar­rays at the end are filled with the filler value to make sure they have the cor­rect length.

looka­head([], 3, null) # => []
looka­head([42], 3, null) # => [[42, null, null, null]]
looka­head([42, 23], 3, null) # => [[42, 23, null, null], [23, null, null, null]]
looka­head([42, 23], 0, null) # => [[42], [23]]

Try slid­ing win­dow would yield an empty ar­ray in each of the ex­amples above.

(inner, constant) mod

Source:

Modify/​Trans­form the given value.

Ap­plys the given value to the given func­tion; after the re­turn value is known, that re­turn value is con­ver­ted into the type of the given para­meter.

const s = new Set([1,2,3,4]);
const z = mod1(s, map(plus(1))); # => new Set([2,3,4,5]),
as­sert(z.con­structor === Set)

(inner, constant) union2

Source:

Curry­able ver­sion of union

Methods

(inner) iter(obj)

Source:

Turn any ob­ject into an iter­ator. Takes ob­jects that im­ple­ment the iter­ator pro­tocol. Plain ob­jects are treated as key-value stores and yield a se­quence of their key value bytes, rep­res­en­ted as size-2 ar­rays.

Any value that is al­lowed as a para­meter for this func­tion shall be con­sidered to be a Se­quence for the pur­pose of this file. This term shall be dis­tin­guished from It­er­able in that it­er­ables must im­ple­ment the iter­ator pro­tocol it­er­able[Sym­bol.iter­ator]().

Parameters:
Name Type Description
obj Object | Iterable | Iterator
Returns:
Type
Iterator
Yields:
The data from the given elements

(generator, inner) range(start, start)

Source:

Gen­er­ates an iter­ator with the nu­meric range [start; end[ In­cludes start but not end.

Parameters:
Name Type Description
start Number
start Number

(inner) range0()

Source:

Like range(a, b) but al­ways starts at 0

(generator, inner) repeat()

Source:

Gen­er­ates an in­fin­ite iter­ator of the given value.

(inner) next(seq) → {Any}

Source:

Ex­tracts the next ele­ment from the iter­ator. If the ele­ment is ex­hausted, Iter­atorEn­ded will be thrown

Parameters:
Name Type Description
seq Sequence

Any se­quence for which iter() is defined

Returns:
Type
Any

(inner) first()

Source:

Ex­tract the first ele­ment from the se­quence

(inner) second()

Source:

Ex­tract the second ele­ment from the se­quence

(inner) seqEq()

Source:

De­term­ine whether the items in two se­quences are equal.

(inner) count()

Source:

De­term­ine the num­ber of ele­ments in an iter­ator. This will try us­ing trySize(), but fall back to it­er­at­ing over the con­tainer and count­ing the ele­ments this way if ne­ces­sary.

(inner) list()

Source:

Turns any se­quence into a list. Short­hand for Ar­ray.from(iter()). This is of­ten util­ized to cache a se­quence so it can be it­er­ated over mul­tiple times.

(inner) uniq()

Source:

Turns any se­quence into a set. Short­hand for new Set(iter()). This of­ten finds prac­tical us­age as a way of re­mov­ing du­plic­ates ele­ments from a se­quence.

(inner) dict()

Source:

Turns any se­quence into an es6 map This is par­tic­u­larly use­ful for con­struct­ing es7 maps from ob­jects...

(inner) obj()

Source:

Turns any se­quence into an ob­ject

(inner) any()

Source:

Test whether any ele­ment in the given se­quence is truthy. Re­turns null if the list is empty.

(inner) all()

Source:

Test whether all ele­ments in the given se­quence are truthy Re­turns true if the list is empty.

(inner) sum()

Source:

Cal­cu­late the sum of a list of num­bers. Re­turns 0 is the list is empty.

(inner) product()

Source:

Cal­cu­late the product of a list of num­bers. Re­turns 1 is the list is empty.

(inner) reverse(seq) → {Array}

Source:

Re­verse a given se­quence

Parameters:
Name Type Description
seq Sequence

Any se­quence for which iter() is defined

Returns:
Type
Array

(generator, inner) enumerate(seq) → {Iterator}

Source:

Ex­tend the given se­quences with in­dexes: Takes a se­quence of val­ues and gen­er­ates a se­quence where each ele­ment is a pair [in­dex, ele­ment];

Parameters:
Name Type Description
seq Sequence

Any se­quence for which iter() is defined

Returns:
Type
Iterator

(inner) takeDef(seq) → {Iterator}

Source:

Cut of the given se­quence at the first un­defined or null value.

Parameters:
Name Type Description
seq Sequence

Any se­quence for which iter() is defined

Returns:
Type
Iterator

(generator, inner) flat(seq)

Source:

Flat­tens a se­quence of se­quences.

into(flat([[1,2], [3,4]]), Ar­ray) # [1,2,3,4]
into(flat({foo: 42}), Ar­ray) # ["foo", 42]
Parameters:
Name Type Description
seq Sequence(Sequence)

Any se­quence for which iter() is defined

(inner) concat()

Source:

Con­cat­en­ate any num­ber of se­quences. This is just a vari­adic alias for flat()

(inner) zipLeast(seq) → {Iterator}

Source:

Zip mul­tiple se­quences. Puts all the first val­ues from se­quences into one sub­list; all the second val­ues, third val­ues and so on. If the se­quences are of dif­fer­ent length, the out­put se­quence will be the length of the shortest se­quence and dis­card all re­main­ing from the longer se­quences...

Parameters:
Name Type Description
seq Sequence

A se­quence of se­quences

Returns:
Type
Iterator

(generator, inner) zip(seq) → {Iterator}

Source:

Zip mul­tiple se­quences. Puts all the first val­ues from se­quences into one sub­list; all the second val­ues, third val­ues and so on. If the se­quences are of dif­fer­ent length, an er­ror will be thrown.

Parameters:
Name Type Description
seq Sequence

A se­quence of se­quences

Returns:
Type
Iterator

(inner) union()

Source:

Com­bine mul­tiple map/​set like ob­jects.

The re­turn type is al­ways the type of the first value. In­tern­ally this just con­cat­en­ates the val­ues from all para­met­ers and then uses into to con­vert the val­ues back to the ori­ginal type.

union({a: 42, b: 23}, new Map([['b', 99]])) => {a: 42, b: 99} union(new Set(1,2,3,4), [4,6,99]) => new Set([1,2,3,4,6,99])AA

Takes any num­ber of val­ues to com­bine.