Global

Members

constant aint

!== as a function

.

!== as a function

constant and

The && operator as a function

.

The && operator as a function

constant append

Given a sequence and a value, append the value to the sequence, yielding a new iterator.

Given a sequence and a value, append the value to the sequence, yielding a new iterator.

constant assign

Set a value in a container.

Set a value in a container. Always returns the given value.

constant Assign

Trait to assign a value in a container like type.

Trait to assign a value in a container like type.

Implemented for Object, String, Array, Map.

Interface

(c: Container, v: Value, k: Key) => void.

Laws

  • Must not be implemented for set-like data structures

Specialization Notes

No implementation provided for String since String is read only.

constant Deepclone

Recursively clone an object.

Recursively clone an object.

Interface

(x: TheValue) => r: TheValue

Laws

  • x !== r
  • x equals r wehre eq is the equals() function.
  • get(r, k) !== get(x, k) for any k.
  • has(r, k) implies has(x, k) for any k.
  • get(r, k) equals get(x, k) for any k wehre eq is the equals() function.
  • The above laws apply recursively for any children.

Specialization Notes

No implementation provided for set: In sets keys and values are the same thing. If we cloned sets deeply, has(orig, key) implies has(clone, key) would be violated and the sets would not be equal after cloning. For the same reason, Map keys are not cloned either!

constant del

Delete an entry with the given key from a container

.

Delete an entry with the given key from a container

constant Delete

Test if a container holds an entry with the given key.

Test if a container holds an entry with the given key.

Interface

(c: Container, k: Key) => Void.

Laws

  • The value must actually be deleted, not set to undefined if possible. Arrays become sparse if a value in their midst is deleted.

Specialization Notes

No implementation provided for String since String is read only. No implementation for Array since has() disregards sparse slots in arrays (so a delete op would be the same as assign(myArray, idx, undefined)) which would be inconsistent.

constant each

Iterate over sequences: Apply the give function to every element in the sequence

.

Iterate over sequences: Apply the give function to every element in the sequence

constant eq

Determine whether two values are equal using the Equals trait.

Determine whether two values are equal using the Equals trait.

This function is a bit more powerful than than the Equals trait itself: First of all it searches for a Equals implementation for both arguments and it falls back to === if none is found. For this reason using eq() is usually preferred over using the Equals trait directly.

constant Equals

Trait to check whether two values are equal.

Trait to check whether two values are equal.

Normally this trait should not be used directly; consider using eq() instead.

This trait should be used only in cases where ===/is() is too strict. Equals is for cases in which the content of two variables or data structures is the same/semantically equivalent.

Interface

(value1: Any, value2: Any) => r: Boolean

Laws

  • Equals.invoke(a, b) <=> Equals.invoke(b, a)

This law seems trivial at first, but one actually needs to take some care to make this work: The trait resolves to the implementation for the first argument! So Equals.invoke(a: Number, b: String) and Equals.invoke(a: String, b: Number) will actually resolve to two different implementations. The easiest way to make this work is just to add a check (a, b) => type(b) === Number to the implementation for number and adding an equivalent check in string. If comparing across types is actually desired (and might return true), I suggest using the same code for both implementations: Consider the following contrive examples:

Equals.impl(Number, (a, b) =>
  type(b) === (String || type(b) === Number)
  && a.toString() === b.toString());
Equals.impl(String, (a, b) =>
  type(b) === (String || type(b) === Number)
  && a.toString() === b.toString());

Specialization notes

Extra implementations provided for Date, RegExp, URL and typed arrays.

Note that for sets: eq(new Set([{}]), new Set([{}])) does not hold true, since in sets keys and values are the same thing and keys always follow === semantics.

constant extend

Generate a sequence by repeatedly calling the same function on the previous value.

Generate a sequence by repeatedly calling the same function on the previous value.

This is often used in conjunction with takeDef or takeWhile to generate a non-infinite sequence.

// Generate an infinite list of all positive integers
extend(0, x => x+1);
// Generate the range of integers [first; last[
const range = (first, last) =>
  takeUntilVal(extend(first, x => x+1), last);

constant extend1

Like extend(), but the resulting sequence does not contain the initial element.

Like extend(), but the resulting sequence does not contain the initial element.

constant filter

Remove values from the sequence based on the given condition.

Remove values from the sequence based on the given condition.

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

constant flattenTree

Flatten trees of any type into a sequence.

Flatten trees of any type into a sequence.

The given function basically has three jobs:

  1. Decide whether a given value in a tree is a node or a leaf (or both)
  2. Convert nodes into sequences so we can easily recurse into them
  3. Extract values from leaves

If the given function does it's job correctly, visit will yield a sequence with all the values from the tree.

The function must return a sequence of values! It is given the current node as well as a callback that that takes a list of child nodes and flattens the given subnodes.

Use the following return values:

flattenTree((node, recurse) => {
  if (isEmptyLeaf()) {
    return [];

  } else if (isLeaf(node)) {
    return [node.value];

  } else if (isMultiLeaf(node)) {
    return node.values;

  } else if (isNode(node)) {
    return recurse(node.childNodes);

  } else if (isLeafAndNode(node)) {
    return concat([node.value], recurse(node.childNodes));
  }
 }
});

constant foldl

Combine all the values from a sequence into one value.

Combine all the values from a sequence into one value.

This function is also often called reduce, because it reduces multiple values into a single value.

Here are some common use cases of the foldl function:

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);

Notice the pattern: We basically take an operator and apply it until the sequence is empty: sum([1,2,3,4]) is pretty much equivalent to 1 + 2 + 3 + 4.

(If you want to get very mathematical here...notice how we basically have an operation and then just take the operation's neutral element as the initial value?)

constant foldr

Like foldl, but right-to-left

.

Like foldl, but right-to-left

constant get

Given a key, get a value from a container.

Given a key, get a value from a container.

constant Get

Trait to get a value from a container like type.

Trait to get a value from a container like type.

Implemented for Object, String, Array, Map.

Interface

(c: Container, k: Key) => v: Value|undefined. Will return undefined if the key could not be found.

Laws

  • Must not be implemented for set-like data structures

constant has

Test if a container includes an entry with the given key

.

Test if a container includes an entry with the given key

constant Has

Test if a container holds an entry with the given key.

Test if a container holds an entry with the given key.

Interface

(c: Container, k: Key) => b: Boolean.

Laws

  • Must not be implemented for set-like data structures

constant Immutable

This is a flag trait that indicates whether a type is immutable.

This is a flag trait that indicates whether a type is immutable.

Since javascript has not real way to enforce absolute immutability this trait considers anything immutable that is hard to mutate or really not supposed to be mutated. Function is considered immutable despite it being possible to assign parameters to functions...

This is used in a couple paces; specifically it is used as a list of types that should be left alone in deepclone and shallowclone.

constant into

Convert values into a given type using the Into trait.

Convert values into a given type using the Into trait. Note that this has inverse parameters compared to the trait (sequence first, type second) for currying purposes.

constant Into

Into can be used to turn sequences back into other types.

Into can be used to turn sequences back into other types.

into is the inverse of iter(), meaning that taking the result of iter() and calling into(), yields the original value.

So in a purely functional language, into(iter(v)) would be a no-op; since we are in javascript, this essentially implements a poor mans shallow copy for some types

const shallowcopy = (v) => into(v, v.constructor);

Interface

`(T: Type/Function, v: Sequence) => r: T

Laws

  • into(v, type(v)) <=> shallowclone(v)

Specialization notes

String: Uses toString() on each value from the sequence and concatenates them into one string... Object: Expects key/value pairs; the keys must be strings; sequences containing the same key multiple times and sequences with bad key/value pairs are considered to be undefined behaviour. The key/value pairs may be sequences themselves. Map: Same rules as for object. Set: Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

Examples

Practical uses of into include converting between types; e.g:

into({foo:  42, bar: 23}, Map) # Map { 'foo' => 42, 'bar' }
into(["foo", " bar"], String) # "foo bar"
into([1,1,2,3,4,2], Set) # Set(1,2,3,4)

Into is also useful to transform values using the functions in this class:

# Remove odd numbers from a set
const st = new Set([1,1,2,2,3,4,5]);
into(filter(st, n => n % 2 == 0), Set) # Set(2,4)

# Remove a key/value pair from an object
const obj = {foo: 42, bar: 5};
into(filter(obj, ([k, v]) => k !== 'foo'), Obj)
# yields {bar: 5}

It can be even used for more complex use cases:

# Merge multiple key/value containers into one sequence:
const seq = concat([[99, 42]], new Map(true, 23), {bar: 13});
into(seq, Map) # Map( 99 => 42, true => 23, bar => 13 )

constant is

=== as a function

.

=== as a function

constant join

Convert each element from a sequence into a string and join them with the given separator.

Convert each element from a sequence into a string and join them with the given separator.

constant lookahead

Almost like trySlidingWindow, but makes sure that every element from the sequence gets it's own subarray, even the last element.

Almost like trySlidingWindow, but makes sure that every element from the sequence gets it's own subarray, even the last element. The arrays at the end are filled with the filler value to make sure they have the correct length.

lookahead([], 3, null) # => []
lookahead([42], 3, null) # => [[42, null, null, null]]
lookahead([42, 23], 3, null) # => [[42, 23, null, null], [23, null, null, null]]
lookahead([42, 23], 0, null) # => [[42], [23]]

Try sliding window would yield an empty array in each of the examples above.

constant map

Lazily transform all the values in a sequence.

Lazily transform all the values in a sequence.

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

constant mapSort

Sort a sequence.

Sort a sequence. The given function must turn map each parameter to a string or number. Objects will be sorted based on those numbers.A If the given parameters are already numbers/strings, you may just use identity as the mapping function.

constant mod

Modify/Transform the given value.

Modify/Transform the given value.

Applys the given value to the given function; after the return value is known, that return value is converted into the type of the given parameter.

const s = new Set([1,2,3,4]);
const z = mod1(s, map(plus(1))); # => new Set([2,3,4,5]),
assert(z.constructor === Set)

constant mul

The * operator as a function

.

The * operator as a function

constant nand

NAND as a function.

NAND as a function.

constant nor

NOR as a function.

NOR as a function.

constant nth

Extract the nth element from the sequence

.

Extract the nth element from the sequence

constant or

The|| operator as a function

.

The|| operator as a function

constant Pairs

Get an iterator over a container.

Get an iterator over a container.

This is different from the Sequence trait in sequence.js in that this always returns pairs, even for lists, sets, strings...

Interface

(c: Container(k: Key, v: Value)) => r: Sequence([k: Key, v: Value], ...).

Specialization Notes

Array like types return index => value, set returns value => value.

constant plus

The + operator as a function

.

The + operator as a function

constant prepend

Given a sequence and a value, prepend the value to the sequence, yielding a new iterator.

Given a sequence and a value, prepend the value to the sequence, yielding a new iterator.

constant reject

Opposite of filter: Removes values from the sequence if the function returns true.

Opposite of filter: Removes values from the sequence if the function returns true.

constant replace

Swap out one value in a container for another

.

Swap out one value in a container for another

constant Replace

Swap out one value in a container for another.

Swap out one value in a container for another.

This trait is implicitly implemented if the container implements Get and Set.

Interface

(c: Container, v: Value, k: Key) => r: Value.

constant Sequence

Trait for any iterable type.

Trait for any iterable type.

Uses the Symbol.iterator Symbol, so this is implemented for any type that implements the iterator protocol.

constant setdefault

Set a default value in a container.

Set a default value in a container.

constant Setdefault

Set a default value in a container.

Set a default value in a container.

This trait is implicitly implemented if the container implements Has, Get and Set.

Interface

(c: Container, v: Value, k: Key) => r: Value.

constant Shallowclone

Shallowly clone an object.

Shallowly clone an object.

Interface

(x: TheValue) => r: TheValue

Laws

  • x !== r
  • get(r, k) === get(x, k) for any k.

Implementation Notes

No-Op implementations are provided for read only primitive types.

constant Size

Trait to determine the size of a container.

Trait to determine the size of a container.

Implemented at least for Object, String, Array, Map, Set.

Interface

Invocation takes the form (c: Container) => i: Integer

Laws

  • i >= 0
  • i !== null && i !== undefined.
  • Must be efficient to execute. No IO, avoid bad algorithmic complexities.

constant skip

Skip elements in a sequence.

Skip elements in a sequence. Throws IteratorEnded if the sequence contains less than no elements.

constant skipWhile

Skips elements in the given sequences until one is found for which the predicate is false.

Skips elements in the given sequences until one is found for which the predicate is false.

constant slidingWindow

Forms a sliding window on the underlying iterator.

Forms a sliding window on the underlying iterator.

slidingWindow([1,2,3,4,5], 3) yields [[1,2,3], [2,3,4], [3,4,5]]

Will throw IteratorEnded if the sequence is shorter than the given window.

constant supports

Test if the given trait has been implemented for the given type

.

Test if the given trait has been implemented for the given type

constant take

Version of tryTake that will throw IteratorEnded if the given iterable is too short.

Version of tryTake that will throw IteratorEnded if the given iterable is too short.

constant takeUntilVal

Cut of the sequence at the point where the given value is first encountered.

Cut of the sequence at the point where the given value is first encountered.

constant takeWhile

Cut off the sequence at the first point where the given condition is no longer met.

Cut off the sequence at the first point where the given condition is no longer met.

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

constant trySkip

Like skip, but returns an exhausted iterator if the sequence contains less than no elements instead of throwing IteratorEnded.

Like skip, but returns an exhausted iterator if the sequence contains less than no elements instead of throwing IteratorEnded.

constant trySlidingWindow

Like slidingWindow, but returns an empty sequence if the given sequence is too short.

Like slidingWindow, but returns an empty sequence if the given sequence is too short.

constant tryTake

Yields an iterator of the first no elements in the given sequence; the resulting iterator may contain less then no elements if the input sequence was shorter than no elements.

Yields an iterator of the first no elements in the given sequence; the resulting iterator may contain less then no elements if the input sequence was shorter than no elements.

constant typedArrays

List of all types that are typed arrays

.

List of all types that are typed arrays

constant uneq

Equivalent to !eq(a, b)

.

Equivalent to !eq(a, b)

constant union2

Curryable version of union

.

Curryable version of union

constant valueSupports

Test if the given trait has been implemented for the given value

.

Test if the given trait has been implemented for the given value

constant xnor

XNOR as a function.

XNOR as a function.

constant xor

XOR as a function.

XOR as a function.

constant zip2

Curryable version of zip

.

Curryable version of zip

constant zipLeast2

Curryable version of zipLeast

.

Curryable version of zipLeast

constant zipLongest

Zip multiple sequences.

Zip multiple sequences. Puts all the first values from sequences into one sublist; all the second values, third values and so on... If the sequences are of different length, the resulting iterator will have the length of the longest sequence; the missing values from the shorter sequences will be substituted with the given fallback value.

constant zipLongest2

Curryable version of zipLongest

.

Curryable version of zipLongest

Methods

all()

Test whether all elements in the given sequence are truthy Returns true if the list is empty.

Test whether all elements in the given sequence are truthy Returns true if the list is empty.

any()

Test whether any element in the given sequence is truthy.

Test whether any element in the given sequence is truthy. Returns null if the list is empty.

assertEquals()

Assert that eq(actual, expected)

.

Assert that eq(actual, expected)

assertUneq()

Assert that !eq(actual, expected)

.

Assert that !eq(actual, expected)

compose(…fns) → {function}

Function composition.

Function composition.

const fn = compose(
  (x) => x+2,
  (x) => x*3
);

console.log(fn(4)); // => 18
Parameters:
Name Type Attributes Description
fns function <repeatable>

Multiple functions

Returns:
function -

All the functions in the sequence composed into one

concat()

Concatenate any number of sequences.

Concatenate any number of sequences. This is just a variadic alias for flat()

count()

Determine the number of elements in an iterator.

Determine the number of elements in an iterator. This will try using trySize(), but fall back to iterating over the container and counting the elements this way if necessary.

curry()

Autocurry a function!

https://en.wikipedia.org/wiki/Currying

Any function that has a fixed number of parameters may be curried! Curried parameters will be in reverse order.

Autocurry a function!

https://en.wikipedia.org/wiki/Currying

Any function that has a fixed number of parameters may be curried! Curried parameters will be in reverse order. This is useful for functional programming, because it allows us to use function parameters in the suffix position when using no curring:

const toNumber = (seq) => map(seq, n => Number(n));

// is the same as

const toNumber = map(n => Number(n))

// or even

const toNumber = map(Number);

Note how in the second version we specified the last parameter first due to currying.

Reverse order only applies in separate invocations:

const sum = (seq) => foldl(seq, 0, (a, b) => a+b);

// is the same as

const sum = foldl(0, (a, b) => a+b);

// or even

concat = sum = foldl(0, plus);

Note how in version two, we specify the parameters in order 2, 3, and then 1:

fn(a, b, c) <=> fn(c)(b)(a) <=> fn(b, c)(a)

deepclone()

Recursively clone an object

.

Recursively clone an object

dict()

Turns any sequence into an es6 map This is particularly useful for constructing es7 maps from objects...

Turns any sequence into an es6 map This is particularly useful for constructing es7 maps from objects...

empty()

Determine if a container is empty.

Determine if a container is empty. Uses size(x) === 0

generator enumerate(seq) → {Iterator}

Extend the given sequences with indexes: Takes a sequence of values and generates a sequence where each element is a pair [index, element];

.

Extend the given sequences with indexes: Takes a sequence of values and generates a sequence where each element is a pair [index, element];

Parameters:
Name Type Description
seq Sequence

Any sequence for which iter() is defined

Returns:
Iterator

exec()

Immediately execute the given function.

Immediately execute the given function. Mostly used as a way to open a scope.

first()

Extract the first element from the sequence

.

Extract the first element from the sequence

generator flat(seq)

Flattens a sequence of sequences.

Flattens a sequence of sequences.

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

Any sequence for which iter() is defined

identity()

Just a function that returns it's argument!

.

Just a function that returns it's argument!

isdef()

Checks whether a value is defined.

Checks whether a value is defined. This function considers all values that are not null and not undefined to be defined

isImmutable()

Test whether a given value is immutable

.

Test whether a given value is immutable

isPrimitive()

Test if a value is primitive

.

Test if a value is primitive

iter(obj) → {Iterator}

Turn any object into an iterator.

Turn any object into an iterator. Takes objects that implement the iterator protocol. Plain objects are treated as key-value stores and yield a sequence of their key value bytes, represented as size-2 arrays.

Any value that is allowed as a parameter for this function shall be considered to be a Sequence for the purpose of this file. This term shall be distinguished from Iterable in that iterables must implement the iterator protocol iterable[Symbol.iterator]().

Parameters:
Name Type Description
obj Object | Iterable | Iterator
Returns:
Iterator

generator keys()

Get an iterator over the keys of a container.

Get an iterator over the keys of a container. Uses pairs(c).

list()

Turns any sequence into a list.

Turns any sequence into a list. Shorthand for Array.from(iter()). This is often utilized to cache a sequence so it can be iterated over multiple times.

next(seq) → {Any}

Extracts the next element from the iterator.

Extracts the next element from the iterator. If the element is exhausted, IteratorEnded will be thrown

Parameters:
Name Type Description
seq Sequence

Any sequence for which iter() is defined

Returns:
Any

not()

! as a function

.

! as a function

obj()

Turns any sequence into an object

.

Turns any sequence into an object

pairs()

Get an iterator over any container; always returns pairs [key, value]

.

Get an iterator over any container; always returns pairs [key, value]

pipe(val, …fns) → {Any}

Pipeline a value through multiple function calls.

Pipeline a value through multiple function calls.

console.log(pipe(
  4,
  (x) => x+2,
  (x) => x*3
));
// => 18
Parameters:
Name Type Attributes Description
val Any

The value to pipe through the functions

fns function <repeatable>

Multiple functions

Returns:
Any

product()

Calculate the product of a list of numbers.

Calculate the product of a list of numbers. Returns 1 is the list is empty.

generator range(start, start)

Generates an iterator with the numeric range [start; end[ Includes start but not end.

Generates an iterator with the numeric range [start; end[ Includes start but not end.

Parameters:
Name Type Description
start Number
start Number

range0()

Like range(a, b) but always starts at 0

.

Like range(a, b) but always starts at 0

generator repeat()

Generates an infinite iterator of the given value.

Generates an infinite iterator of the given value.

reverse(seq) → {Array}

Reverse a given sequence

.

Reverse a given sequence

Parameters:
Name Type Description
seq Sequence

Any sequence for which iter() is defined

Returns:
Array

second()

Extract the second element from the sequence

.

Extract the second element from the sequence

seqEq()

Determine whether the items in two sequences are equal.

Determine whether the items in two sequences are equal.

shallowclone()

Shallowly clone an object

.

Shallowly clone an object

size()

Determine the size of a container.

Determine the size of a container. Uses the Size trait

sum()

Calculate the sum of a list of numbers.

Calculate the sum of a list of numbers. Returns 0 is the list is empty.

takeDef(seq) → {Iterator}

Cut of the given sequence at the first undefined or null value.

Cut of the given sequence at the first undefined or null value.

Parameters:
Name Type Description
seq Sequence

Any sequence for which iter() is defined

Returns:
Iterator

type()

Determine type of an object.

Determine type of an object. Like obj.constructor, but won't fail for null/undefined and just returns the value itself for those. This is a useful feature for code that is supposed to be null/undefined-safe since those need not be special cased.

typeIsImmutable()

Test whether instance of a given type is immutable

.

Test whether instance of a given type is immutable

typename()

Given a type, determine it's name.

Given a type, determine it's name. This is useful as a replacement for val.constructor.name, since this can deal with null and undefined.

union()

Combine multiple map/set like objects.

Combine multiple map/set like objects.

The return type is always the type of the first value. Internally this just concatenates the values from all parameters and then uses into to convert the values back to the original 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 number of values to combine.

uniq()

Turns any sequence into a set.

Turns any sequence into a set. Shorthand for new Set(iter()). This often finds practical usage as a way of removing duplicates elements from a sequence.

generator values()

Get an iterator over the values of a container.

Get an iterator over the values of a container. Uses pairs(c).

withFunctionName(name, fn, Just)

Manually assign a name to a function.

Manually assign a name to a function.

Parameters:
Name Type Description
name String

The new name of the function.

fn function

The function to assign a name to

Just function

returns fn again.

generator zip(seq) → {Iterator}

Zip multiple sequences.

Zip multiple sequences. Puts all the first values from sequences into one sublist; all the second values, third values and so on. If the sequences are of different length, an error will be thrown.

Parameters:
Name Type Description
seq Sequence

A sequence of sequences

Returns:
Iterator

zipLeast(seq) → {Iterator}

Zip multiple sequences.

Zip multiple sequences. Puts all the first values from sequences into one sublist; all the second values, third values and so on. If the sequences are of different length, the output sequence will be the length of the shortest sequence and discard all remaining from the longer sequences...

Parameters:
Name Type Description
seq Sequence

A sequence of sequences

Returns:
Iterator