JFL - JavaScript Standard Functional Library
This JavaScript library aims to compliment the language to provide a single dependency for writing most business logic code. It is fully statically typed to work well with both Flow and TypeScript.
Note on types
This library is centered around basic collection types available in JavaScript: Arrays, Maps and Sets. These are all KeyedCollections (Arrays have indices and Sets have the same keys as values). But for simplicity many functions accept values which match the simpler Collection interface, which only declares that there are values.
Additionally the library definition uses the type aliases $Array, $Map and $Set for the read-only versions of Array, Map and Set (these are declared as $ReadOnly... in Flow and ReadOnly... in TypeScript).
(jfl)
This is the main module from which you can easily import all the others, plus a few utilities for working in Flow/TypeScript in general.
Type
nullthrows
Returns value if it's not null or undefined, throws otherwise.
Useful for coercing the nullable type of value to non-nullable when using Flow.
nullthrows<T>value: ?Tmessage?: string = 'Got unexpected null or undefined'): T
// throws// 'a'
invariant
Throws an error with message if condition is false.
Both Flow and TypeScript will consider the condition to be an assertion and will infer types correspondingly.
: void
// throws// no-op
Ar (array)
This module provides functions which operate on collections (Arrays, Maps, Sets) and return read-only (immutable) Arrays.
Construct
$Ar
Create an Array.
Prefer array literal `[1, 2, 3]`. This function always returns a reference to the same empty array when called with no arguments.
$Ar<V>...args: $Array<V>: $Array<V>
// [1, 2, 3]
Ar.from
Convert any collection of values to an Array of values.
Note that this is not a way to clone an Array, if passed an Array, the same array will be returned.
from<V>collection: Collection<V>: $Array<V>
Ar // [1, 2, 3]Ar // [1, 2, 3]
Ar.fromAsync
Convert any collection of awaitable promises of values to a single promise of an Array of values.
fromAsync<V>collection: Collection<Promise<V>>: Promise<$Array<V>>
await Ar // [1, 2]
Ar.keys
Convert any collection with keys to an Array of keys.
Notably the keys of a Set are just its values. The keys of an Array are its indices.
keys<K>collection: KeyedCollection<K any>: $Array<K>
Ar // [0, 1]Ar // ['a', 'b']Ar
Ar.entries
Convert any collection with keys to an Array of key value pairs.
Notably the keys of a Set are just its values. The keys of an Array are its indices.
entries<K V>collection: KeyedCollection<K V>: $Array<K V>
Ar // [[0, 5], [1, 6]]Ar // [['a', 2], ['b', 3]]Ar
Ar.range
Create an Array of numbers.
The start of the range is inclusive, the end is exclusive. By default increments by 1.
: $Array<number>
Ar // [1, 2, 3, 4, 5]Ar // [-0.5, 0, 0.5]
Ar.rangeInclusive
Create an Array of numbers.
A version of Ar.range where the end is inclusive.
: $Array<number>
Ar // [-0.5, 0, 0.5]
Ar.rangeDescending
Create an Array of numbers.
A version of Ar.range where the array of numbers has decreasing order. By default increments by -1.
: $Array<number>
Ar // [5, 4, 3, 2]Ar // [2, 1.8, 1.6, 1.4, 1.2]
Ar.rangeDynamic
Create an Array of numbers.
A version of Ar.range where the array of numbers has increasing or decreasing order, depending on given range limits. Both limits are inclusive.
: $Array<number>
Ar // [2, 4, 6]Ar // [6, 4, 2]
Ar.repeat
Create an Array filled with a count of given values.
The value will be referenced, not cloned.
repeat<V>value: V count: number: $Array<V>
Ar // ["a", "a", "a", "a"]
Ar.fill
Create an Array filled with count results of calling fn.
fn takeFirst as the first argument the index where the current invocation's result will be placed.
fill<V>count: number V: $Array<V>
Ar // [0, 1, 2, 3]
Ar.fillAsync
Create a promise of an Array filled with count results of calling fn.
fn takeFirst as the first argument the index where the current invocation's result will be placed.
fillAsync<V>count: numberPromise<V>: Promise<$Array<V>>
await Ar // [0, 1, 2, 3]
Ar.generate
Create an Array using a seed value and a function which given the seed returns an item to be contained in the array and a new seed value.
To mark the end of the array, fn must return null or undefined.
generate<V S>seed: S ?V S): $Array<V>
Ar // [2, 4, 16]
Ar.mutable
Convert any collection of values to a mutable Array of values.
If an Array is given it will be cloned.
This function is useful for complicated or performance sensitive computation inside a function. Avoid passing arrays as mutable around your codebase to prevent bugs.
mutable<V>collection: Collection<V>: Array<V>
Ar // [1, 2, 3]
Check
Ar.equals
Returns whether given Arrays are equal.
All items must be strictly equal.
equals<V>array: $Array<V>...arrays: $Array<$Array<V>>: boolean
Ar // true
Ar.equalsNested
Returns whether given Arrays and any nested collections are equal.
Any contained collections must deeply equal, all other items must be strictly equal.
equalsNested<V>array: $Array<V>...arrays: $Array<$Array<V>>: boolean
Ar // true
Select
Ar.filter
Create a new array by filtering out values from `collection for which predicateFn returns false.
filter<K V>collection: KeyedCollection<K V>boolean: $Array<V>
Ar // [1, 3]
Ar.filterAsync
Create a promise of an Array by filtering out values in collection for which async predicateFn returns false.
Executes predicateFn on all items in collection concurrently.
: Promise<$Array<V>>
await Ar // [1, 3]
Ar.filterNulls
Create a new array by filtering out nulls and undefineds from collection.
Here because its type is more specific then the generic filter function.
filterNulls<V>collection: Collection<?V>): $Array<V>
Ar // [1, 3]
Ar.filterKeys
Create an Array of keys corresponding to values passing given predicateFn.
filterKeys<K V>collection: KeyedCollection<K V>boolean: $Array<K>
Ar // [1, 3]
Ar.unique
Create an Array of values from collection with each value included only once.
unique<V>collection: Collection<V>: $Array<V>
Ar // [1]
Ar.uniqueBy
Create an Array of values from collection with each value included only once, where value equivalence is determined by calling identityFn on each value. Later values overwrite previous ones.
uniqueBy<K V>collection: KeyedCollection<K V>mixed: $Array<V>
Ar // [2, 7]
Ar.takeFirst
Create an Array containing the first n items of collection.
Throws if n is negative.
takeFirst<V>collection: Collection<V> n: number: $Array<V>
Ar // [1, 2]
Ar.dropFirst
Create an Array containing all but the first n items of collection.
Throws if n is negative.
dropFirst<V>collection: Collection<V> n: number: $Array<V>
Ar // [3]
Ar.takeLast
Create an Array containing the last n items of collection.
takeLast<V>collection: Collection<V> n: number: $Array<V>
Ar // [2, 3]
Ar.dropLast
Create an Array containing all but the last n items of collection.
dropLast<V>collection: Collection<V> n: number: $Array<V>
Ar // [1]
Ar.takeFirstWhile
Create an Array containing all the items of collection preceding the item for which predicateFn returns false.
takeFirstWhile<K V>collection: KeyedCollection<K V>boolean: $Array<V>
Ar // [1]
Ar.dropFirstWhile
Create an Array containing all the items of collection following and including the first item for which predicateFn returns false.
dropFirstWhile<K V>collection: KeyedCollection<K V>boolean: $Array<V>
Ar // [3, 4, 7]
Ar.takeLastWhile
Create an Array containing all the items of collection following the first item when iterating from the end for which predicateFn returns false.
takeLastWhile<V>collection: Collection<V>boolean: $Array<V>
Ar // [5, 7]
Ar.dropLastWhile
Create an Array containing all the items of collection preceding and including the first item when iterating from the end for which predicateFn returns false.
dropLastWhile<V>collection: Collection<V>boolean: $Array<V>
Ar // [1, 3, 4]
Divide
Ar.chunk
Create an array of Arrays which are chunks of given collection of given size.
If the collection doesn't divide evenly, the final chunk will be smaller than the rest.
chunk<V>collection: Collection<V>size: number: $Array<$Array<V>>
Ar // [[1, 2], [3, 4], [5]]
Ar.partition
Create a tuple of Arrays containing items of collection which match and don't match predicateFn respectively.
More effecient than using multiple Ar.filter calls.
partition<K V>collection: KeyedCollection<K V>boolean: $Array<V> $Array<V>
Ar // [[2, 4], [1, 3]]
Ar.slice
Create an Array containing a subset of values in collection.
Note that this is not a way to clone an Array, if given an Array and indices corresponding to its full size it returns the original array.
Either index can be negative, in which case they are counted from the end of the collection, with last element being at index `-1`.
slice<V>collection: Collection<V>startIndexInclusive: numberendIndexExclusive?: number: $Array<V>
Ar // [2, 3]Ar // [3, 4]
Ar.splice
Create an Array containing a subset of values in collection with any given items added, with deleteCount original values removed.
Note that unlikely Array.prototype.splice this function returns the new array, not the deleted items.
splice<V>collection: Collection<V>startIndex: numberdeleteCount?: number...items: $Array<V>: $Array<V>
Ar // [1, 5, 6, 4]
Ar.splitAt
Create a tuple of arrays containing the first n items and all but the first n items of given collection.
splitAt<V>collection: Collection<V>n: number: $Array<V> $Array<V>
Ar // [[1, 2], [3]]
Ar.span
Create two arrays, the first containing all the items of collection preceding the first item for which predicateFn returns false, the second containing the rest.
span<K V>collection: KeyedCollection<K V>boolean: $Array<V> $Array<V>
Ar // [[1], [3, 4, 7]]
Combine
Ar.prepend
Create a new array containing item followed values of collection.
prepend<V>collection: Collection<V> item: V: $Array<V>
Ar // [1, 2, 3]
Ar.append
Create a new array containing values of collection followed by item.
append<V>collection: Collection<V> item: V: $Array<V>
Ar // [1, 2, 3]
Ar.concat
Concatenate multiple arrays together.
concat<V>...collections: $Array<Collection<V>>: $Array<V>
Ar // [1, 2, 3, 4]
Ar.flatten
Concatenate a collection of arrays together.
flatten<V>collectionOfArrays: Collection<Collection<V>>: $Array<V>
Ar // [1, 2, 3, 4]
Ar.zip
Join collections into an Array of tuples of values from each collection.
The resulting array has the same length as the smallest given collection. Excess values are ignored.
zip<Cs: $Array<Collection<mixed>>>...collections: Cs: $Array<TupleOfValues<Cs>>
Ar // [[1, 'a', 5], [2, 'b', 6]]
Ar.zipWith
Join multiple collections into an Array of values resulting from calling fn on items from each collection.
Note that this function has unusual order of arguments because JavaScript enforces that the rest parameter is the last one. The resulting array has the same length as the smallest given collection. Excess values are ignored.
zipWith<I Cs: $Array<Collection<I>> O>O...collections: Cs: $Array<O>
Ar // [5, 12, 21]
Ar.unzip
Join a collection of tuples into a tuple of Arrays.
unzip<T: $Array<mixed>>collection: Collection<T>: $TupleMap<T <V> $Array<V>>
Ar // [[1, 2], ['a', 'b'], [5, 6]]
Ar.product
Join collections into an Array of tuples of values of all combinations from each collection.
The resulting array has the length which is the product of the lengths of each collection.
product<Cs: $Array<Collection<mixed>>>...collections: Cs: $Array<TupleOfValues<Cs>>
Arproduct1 2 'a' 'b' // [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
Transform
Ar.map
Create a new array by calling given fn on each value of collection.
map<KFrom VFrom VTo>collection: KeyedCollection<KFrom VFrom>VTo: $Array<VTo>
Ar // [2, 4]
Ar.mapAsync
Create a promise of an Array by calling given async fn on each value of collection.
Executes fn on all items in collection concurrently.
mapAsync<KFrom VFrom VTo>collection: KeyedCollection<KFrom VFrom>Promise<VTo>: Promise<$Array<VTo>>
await Ar // [2, 4]
Ar.mapMaybe
Create a new array by calling given fn on each value of collection and and including the result if it is not null or undefined.
Equivalent to using map followed by filterNulls, for simplicity and improved performance.
mapMaybe<KFrom VFrom VTo>collection: KeyedCollection<KFrom VFrom>?VTo): $Array<VTo>
Ar // [1, 9]
Ar.mapFlat
Create a new array by calling given fn on each value of collection and flattening the results.
Equivalent to using map followed by flatten, for simplicity and improved performance.
mapFlat<KFrom VFrom VTo>collection: KeyedCollection<KFrom VFrom>Collection<VTo>: $Array<VTo>
Ar // [0, 2, 1, 3]
Ar.scan
Create an Array of values based on a reduction of given collection.
Similar to Cl.reduce but instead of returning the final value accumulates all the intermediate accumulators.
scan<I O>collection: Collection<I>initialValue: OO: $Array<O>
Ar // [1, 3, 6, 10]
Order
Ar.reverse
Create an Array containing the items of collection in reverse order.
reverse<V>collection: Collection<V>: $Array<V>
Ar // [3, 2, 1]
Ar.sort
Create an Array of values in collection sorted.
The result of calling compareFn on values a and b determines their order: negative number: a, b positive number: b, a zero: the order stays the same as it was in collection The default compareFn is `(a, b) => a > b ? 1 : a < b ? -1 : 0`, which sorts numbers and strings in ascending order (from small to large, from early in the alphabet to later in the alphabet).
This sort preserves the order of elements when compareFn returns 0 at the cost of using more memory.
sort<K V>collection: KeyedCollection<K V>compareFn?:aItem: VbItem: VaKey: KbKey: Knumber = defaultCompareFn: $Array<V>
Ar // [1, 2, 3, 4]Ar // ['a', 'b', 'c', 'd']
Ar.sortBy
Create an Array of values in collection sorted by the scalar computed by calling scalarFn on each value.
The result of calling compareFn on scalars a and b determines the order of the corresponding values: negative number: a, b positive number: b, a zero: the order stays the same as it was in collection The default compareFn is `(a, b) => a > b ? 1 : a < b ? -1 : 0`, which sorts numbers and strings in ascending order (from small to large, from early in the alphabet to later in the alphabet).
This sort preserves the order of elements when compareFn returns 0 at the cost of using more memory.
sortBy<K V S>collection: KeyedCollection<K V>ScompareFn?: number = defaultCompareFn: $Array<V>
Ar // [3, 4, 1, 2]
Ar.sortUnstable
Create an Array of values in collection sorted.
This sort doesn't preserve the order of elements when compareFn returns 0 and is more memory efficient than Ar.sort.
The result of calling compareFn on values a and b determines their order: negative number: a, b positive number: b, a zero: the order is undetermined The default compareFn is `(a, b) => a > b ? 1 : a < b ? -1 : 0`, which sorts numbers and strings in ascending order (from small to large, from early in the alphabet to later in the alphabet).
sortUnstable<V>collection: Collection<V>compareFn?: number = defaultCompareFn: $Array<V>
Ar // 1, 2, 3, 4
Cl (collection)
This module provides functions which operate on collections (Arrays, Maps, Sets) and return a scalar or key/value type.
Check
Cl.equals
Returns whether given collections are equal.
All items must be strictly equal.
equals<V C: Collection<V>>first: C...rest: $Array<C>: boolean
Cl // true
Cl.equalsNested
Returns whether given collections and any nested collections are equal.
Any contained collections must deeply equal, all other items must be strictly equal.
equalsNested<C: mixed>first: C ...rest: $Array<C>: boolean
Cl // true
Cl.isEmpty
Returns true when collection is empty.
isEmpty<V>collection: Collection<V>: boolean
Cl // trueCl // trueCl // true
Cl.contains
Returns whether given collection contains given value.
contains<V>collection: Collection<V> value: V: boolean
Cl // trueCl // trueCl // true
Cl.containsKey
Returns whether given key exists in keyed collection.
containsKey<K V>collection: KeyedCollection<K V>key: K: boolean
Cl // trueCl // trueCl // true
Cl.any
Returns whether some values in collection satisfy predicateFn.
When no predicateFn is given returns true when collection contains at least one true value.
: boolean
: boolean
Cl // trueCl // true
Cl.every
Returns whether all values in collection satisfy predicateFn.
When no predicateFn is given returns true when collection contains only true values.
: boolean
: boolean
Cl // trueCl // trueCl // true
Cl.isSorted
Returns whether given collection is sorted.
The result of calling compareFn on values a and b determines their order: negative number: a, b positive number: b, a zero: the order stays the same as it was in collection The default compareFn is `(a, b) => a > b ? 1 : a < b ? -1 : 0`, which sorts numbers and strings in ascending order (from small to large, from early in the alphabet to later in the alphabet).
isSorted<V>collection: Collection<V>compareFn?: number = defaultCompareFn: boolean
Cl // trueCl // true
Cl.isSortedBy
Returns whether given collection is sorted by the scalar computed by calling scalarFn on each value.
The result of calling compareFn on values a and b determines their order: negative number: a, b positive number: b, a zero: the order stays the same as it was in collection The default compareFn is `(a, b) => a > b ? 1 : a < b ? -1 : 0`, which sorts numbers and strings in ascending order (from small to large, from early in the alphabet to later in the alphabet).
isSortedBy<V S>collection: Collection<V>ScompareFn?: number = defaultCompareFn: boolean
Cl // true
Select
Cl.find
Returns the first value for which predicateFn returns true in collection, if any.
find<V>collection: Collection<V>boolean: ?V
Cl // nullCl // 3
Cl.findX
Returns first value for which predicateFn returns true in collection.
findX<V>collection: Collection<V>boolean: V
Cl // 3
Cl.findKey
Returns the key of the first value for which predicateFn returns true in collection, if any.
findKey<K V>collection: KeyedCollection<K V>boolean: ?K
Cl // 2
Cl.findKeyX
Returns the key of the first value for which predicateFn returns true in collection.
findKeyX<K V>collection: KeyedCollection<K V>boolean: K
Cl // 2
Cl.first
Returns the first value in collection if it's not empty, null otherwise.
first<V>collection: Collection<V>: ?V
Cl // nullCl // 1
Cl.firstX
Returns the first value in collection if it's not empty, throws otherwise.
firstX<V>collection: Collection<V>: V
Cl // 1
Cl.onlyX
Returns the one and only value in collection, throws otherwise.
onlyX<V>collection: Collection<V>: V
Cl // 1Cl // throwsCl // throws
Cl.last
Returns the last value in collection if it's not empty, null otherwise.
last<V>collection: Collection<V>: ?V
Cl // nullCl // 3
Cl.lastX
Returns the last value in collection if it's not empty, throws otherwise.
lastX<V>collection: Collection<V>: V
Cl // 3
Cl.at
Returns the value at given iteration index or null.
For accessing values using corresponding keys use Map.prototype.get or Set.prototype.has, which are all correctly typed.
at<V>collection: Collection<V> index: number: ?V
Cl // nullCl // 'c'
Cl.atX
Returns the value at given iteration index or throws.
atX<V>collection: Collection<V> index: number: V
Cl // 'c'
Cl.atFromEnd
Returns the value at index as if iterating through the collection in reverse order or null.
atFromEnd<V>collection: Collection<V> index: number: ?V
Cl // nullCl // 4Cl // 1
Cl.atFromEndX
Returns the value at index as if iterating through the collection in reverse order or throws.
atFromEndX<V>collection: Collection<V> index: number: V
Cl // 4Cl // 1
Cl.atDynamic
Return element at index counting from start if it's positive and counting from end if it's negative, with last element being at index `-1`.
atDynamic<V>collection: Collection<V> index: number: ?V
Cl // 1Cl // 3
Cl.firstKey
Returns the first key in collection if it's not empty, null otherwise.
firstKey<K V>collection: KeyedCollection<K V>: ?K
Cl // nullCl // 'a'
Cl.firstKeyX
Returns the first key in collection if it's not empty, throws otherwise.
firstKeyX<K V>collection: KeyedCollection<K V>: K
Cl // 1
Cl.lastKey
Returns the last key in collection if it's not empty, null otherwise.
lastKey<K V>collection: KeyedCollection<K V>: ?K
Cl // nullCl // 'b'
Cl.lastKeyX
Returns the last key in collection if it's not empty, throws otherwise.
lastKeyX<K V>collection: KeyedCollection<K V>: K
Cl // 'b'
Transform
Cl.forEach
Execute fn for every value and key in collection.
forEach<K V>collection: KeyedCollection<K V>void: void
Cl // void
Cl.reduce
Reduce the collection to a single value using fn.
If no initialValue is passed in, the collection must be non-empty.
: V
: A
Cl // 9
Mp (map)
This module provides functions which operate on collections (Arrays, Maps, Sets) and return read-only (immutable) Maps.
Construct
$Mp
Create a Map.
If your keys aren't strings, prefer Mp.of.
$Mp<K: string V>object?: key: K: V: $Map<K V>
// Map {a => 1, b => 2, c => 3}
Mp.of
Create a Map from given pairs of keys and values.
of<K V>...pairs: $Array<K V>: $Map<K V>
Mp // Map {0 => 2, 4 => 2}
Mp.from
Convert any keyed collection to a Map.
Note that this is not a way to clone a Map, if passed a Map, the same map will be returned.
from<K V>collection: KeyedCollection<K V>: $Map<K V>
Mp // Mp.of([0, 1], [1, 2], [2, 3])Mp // $Mp({a: 'a', b: 'b', c: 'c'})
Mp.fromValues
Create a Map where each value comes from collection and its key is the result of calling getKey on it.
fromValues<KFrom KTo VTo>collection: KeyedCollection<KFrom VTo>KTo: $Map<KTo VTo>
Mp // Mp.of([4, 2], [9, 3])
Mp.fromKeys
Create a Map where each key comes from collection and its value is the result of calling getValue on it.
fromKeys<KFrom KTo VTo>collection: KeyedCollection<KFrom KTo>VTo: $Map<KTo VTo>
Mp // Mp.of([2, 4], [3, 9])
Mp.fromKeysAsync
Create a promise of a Map where each key comes from collection and its value is the result of calling getValue on it.
: Promise<$Map<KTo, VTo>>
await Mp // Mp.of([2, 4])
Mp.fromEntries
Create a Map from a collection of entries, i.e. (key, value) pairs.
fromEntries<K V>collection: Collection<K V>: $Map<K V>
Mp // Mp.of([2, 3])
Mp.zip
Create a Map from given keys and values.
If there are more keys than values or vice versa, ignores the excess items.
zip<K V>keys: Collection<K>values: Collection<V>: $Map<K V>
Mp // $Mp({a: 3, b: 4})
Mp.toObject
Create an Object from a string-keyed Map.
toObject<K: string V>collection: KeyedCollection<K V>: key: K: V
Mp // {a: 1, b: 2}
Mp.mutable
Convert any keyed collection to a mutable Map.
If a Map is given, it will be cloned.
mutable<K V>collection: KeyedCollection<K V>: Map<K V>
Mp // Map {a => 1, b => 2}
Check
Mp.equals
Returns whether given Maps are equal.
All values and keys must be strictly equal.
equals<K V>map: $Map<K V>...maps: $Array<$Map<K V>>: boolean
Mp // true
Mp.equalsOrderIgnored
Returns whether given Maps contain the same key/value pairs.
All values and keys must be strictly equal.
equalsOrderIgnored<K V>map: $Map<K V>...maps: $Array<$Map<K V>>: boolean
Mp // true
Mp.equalsNested
Returns whether given Maps are equal.
Any collection values or keys must deeply equal, all other values and keys must be strictly equal.
equalsNested<K V>map: $Map<K V>...maps: $Array<$Map<K V>>: boolean
Mp // true
Combine
Mp.set
Create a new Map by adding or replacing value under key in given keyed collection.
set<K V>collection: KeyedCollection<K V>key: Kvalue: V: $Map<K V>
Mp // $Mp({a: 1, b: 2})
Mp.merge
Create a new Map by merging all given collections. Later values will override earlier values.
merge<K V>...collections: $Array<KeyedCollection<K V>>: $Map<K V>
Mp // $Mp({a: 2, b: 2, c: 3})
Select
Mp.getX
Returns the value in map for given key or throws.
If you don't know whether the map contains the key use Map.prototype.get.
getX<K V>map: $Map<K V> key: K: V
Mp // 2
Mp.diffByKey
Create a new Map which has all the keys and corresponding values from collection except for the keys that appear in any of the given collections.
diffByKey<K V>collection: KeyedCollection<K V>...collections: $Array<KeyedCollection<K V>>: $Map<K V>
Mp // $Mp({a: 1})
Mp.filter
Create a new Map by filtering out keys and values for which predicateFn returns false.
filter<K V>collection: KeyedCollection<K V>boolean: $Map<K V>
Mp // $Mp({a: 1})Mp // Mp.of([3, 4])
Mp.filterAsync
Create a promise of a Map by filtering out values in collection for which async predicateFn returns false.
Executes predicateFn on all key value pairs in collection concurrently.
: Promise<$Map<K, V>>
Mp // $Mp({0: 1, 2: 3})
Mp.filterNulls
Create a new Map by filtering out null and undefined values.
Here because its type is more specific then the generic filter function.
filterNulls<K V>collection: KeyedCollection<K ?V>): $Map<K V>
Mp // Mp.of([0, 1], [2, 3])
Mp.selectKeys
Create a new Map which has all the keys and corresponding values from map for the keys that appear in keys.
The order of the keys in the resulting map is the order in which they appear first in keys.
selectKeys<K V>collection: KeyedCollection<K V>keys: Collection<K>: $Map<K V>
Mp // $Mp({c: 3, b: 2})
Mp.unique
Create a Map of values from collection with each value included only once.
Later keys for the same value overwrite previous ones.
unique<K V>collection: KeyedCollection<K V>: $Map<K V>
Mp // $Mp({c: 1, b: 2})
Mp.uniqueBy
Create a Map of values from collection with each value included only once, where value equivalence is determined by calling identityFn on each value. Later values and keys overwrite previous ones.
uniqueBy<K V>collection: KeyedCollection<K V>mixed: $Map<K V>
Mp // $Mp({c: 3, b: 2})
Mp.takeFirst
Create a Map containing the first n key value pairs of collection.
takeFirst<K V>collection: KeyedCollection<K V>n: number: $Map<K V>
Mp // $Mp({a: 1, b: 2})
Mp.dropFirst
Create a Map containing all but the first n key value pairs of collection.
dropFirst<K V>collection: KeyedCollection<K V>n: number: $Map<K V>
Mp // $Mp({c: 3})
Transform
Mp.map
Create a new Map by calling given fn on each value and key of collection.
map<KFrom VFrom VTo>collection: KeyedCollection<KFrom VFrom>VTo: $Map<KFrom VTo>
Mp // $Mp({a: 2, b: 4})
Mp.mapAsync
Create a promise of a Map by calling given async fn on each value and key of collection.
Executes fn on all items in collection concurrently.
: Promise<$Map<KFrom, VTo>>
await Mp // $Mp({a: 2})
Mp.mapMaybe
Create a new Map by calling given fn on each value and key of collection and and including the result if it is not null or undefined.
Equivalent to using map followed by filterNulls, for simplicity and improved performance.
mapMaybe<KFrom VFrom VTo>collection: KeyedCollection<KFrom VFrom>?VTo): $Map<KFrom VTo>
Mp // $Mp()
Mp.mapFlat
Create a new Map by calling given fn on each value and key of collection and flattening the results.
Equivalent to using map followed by flatten, for simplicity and improved performance.
mapFlat<KFrom KTo VFrom VTo>collection: KeyedCollection<KFrom VFrom>KeyedCollection<KTo VTo>: $Map<KTo VTo>
Mp // Mp.of([2, 'a'], [4, 'a'])
Mp.mapToEntries
Create a new Map by calling given fn on each value and key of collection.
fn must return new entries to populate the map.
mapToEntries<KFrom VFrom KTo VTo>collection: KeyedCollection<KFrom VFrom>KTo VTo: $Map<KTo VTo>
Mp // $Mp({a: 0, b: 1})
Mp.pull
Create a new Map using keys provided by keyFn and values provided by valueFn applied to each key/value of collection.
When keyFn returns the same key for multiple values only the last value will be present in the new Map. Values for which keyFn returns null or undefined are ommited.
pull<KFrom VFrom KTo VTo>collection: KeyedCollection<KFrom VFrom>?KTovalueFn: VTo: $Map<KTo VTo>
Mp // Mp.of([0, 4], [1, 9])
Mp.group
Create a new Map using keys provided by keyFn and values provided by valueFn applied to each key/value of collection. Values with identitical keys are grouped into Arrays.
Values for which keyFn returns null or undefined are ommited.
: $Map<V, $Array<V>>
: $Map<KTo, $Array<VTo>>
Mp // Mp.of([1, [1, 1]], [3, [3]])Mp // Mp.of([1, [1, 3]], [0, [2]])
Mp.flip
Create a new Map with keys and values being the values and keys of collection respectively.
flip<K V>collection: KeyedCollection<K V>: $Map<V K>
Mp // $Mp({A: 'a', B: 'b'})
Mp.countValues
Create a new Map with keys being the values of collection and values being the number of times each value occured in collection.
undefined and null are valid values of collection.
countValues<V>collection: Collection<V>: $Map<V number>
Mp // $Mp({x: 2, y: 1})
Mp.flatten
Create a new Map by concatenating all keyed collections in given collection.
flatten<K V>collection: Collection<KeyedCollection<K V>>: $Map<K V>
Mp // $Mp({a: 1, b: 2, c: 3})
Divide
Mp.chunk
Create an array of Maps which are chunks of given collection of given size.
If the collection doesn't divide evenly, the final chunk will be smaller than the rest.
chunk<K V>collection: KeyedCollection<K V>size: number: $Array<$Map<K V>>
Mp // [$Mp({a: 1, b: 2}), $Mp({c: 3})]
Mp.partition
Create a tuple of Maps containing keys and items of collection which match and don't match predicateFn respectively.
More effecient than using multiple Mp.filter calls.
partition<K V>collection: KeyedCollection<K V>boolean: $Map<K V> $Map<K V>
Mp // [$Mp(), $Mp({a: 2})]
Ordering
Mp.reverse
Create a Map containing the keys and items of collection in reverse order.
reverse<K V>collection: KeyedCollection<K V>: $Map<K V>
Mp // $Mp({c: 3, b: 2, a: 1})
Mp.sort
Create a Map of keys and values in collection sorted by value.
The result of calling compareFn on values a and b determines their order: negative number: a, b positive number: b, a zero: the order stays the same as it was in collection The default compareFn is `(a, b) => a > b ? 1 : a < b ? -1 : 0`, which sorts numbers and strings in ascending order (from small to large, from early in the alphabet to later in the alphabet).
sort<K V>collection: KeyedCollection<K V>compareFn?:aItem: VbItem: VaKey: KbKey: Knumber = defaultCompareFn: $Map<K V>
Mp // $Mp({b: 1, c: 2, a: 3})Mp // $Mp({z: 'a', y: 'b', x: 'c'})
Mp.sortBy
Create a Map of keys and values in collection sorted by the scalar computed by calling scalarFn on each value and key.
The result of calling compareFn on scalars a and b determines the order of the corresponding values: negative number: a, b positive number: b, a zero: the order stays the same as it was in collection The default compareFn is `(a, b) => a > b ? 1 : a < b ? -1 : 0`, which sorts numbers and strings in ascending order (from small to large, from early in the alphabet to later in the alphabet).
sortBy<K V S>collection: KeyedCollection<K V>ScompareFn?: number = defaultCompareFn: $Map<K V>
Mp // $Mp({b: 1, c: 2, a: 3})
Mth (math)
This module provides functions which complement methods of Math and Number built-ins or operate on collections (Arrays, Maps, Sets) and return numbers.
Check
Mth.isNumber
Returns whether given value is a number.
Use these methods to check that a number `Number.isFinite(x)` is not a NaN or Infinity `Number.isInteger(x)` is an integer (including a possibly rounded large one) `Number.isSafeInteger(x)` is an integer (in representable range) `Number.isNaN(x)` is a NaN (such as the result of `Math.sqrt(-1)`)
: bool
Mth // false
Operators
Mth.pmod
Returns the remainder of dividing numerator by divisor, unlike the `%` operator the result will always be positive.
: number
Mth // 2
Mth.divx
Returns the result of dividing numerator by divisor. Throws an error if divisor is 0.
: number
Mth // throws an error
Mth.idivx
Returns the integer division of numerator by divisor. Throws an error if divisor is 0.
: number
Mth // throws an error
Mth.clamp
Returns value if at least min, otherwise min, and at most max, otherwise max.
: number
Mth // 42Mth // 0Mth // 100
Collections
Mth.min
Returns the smallest of all values in collection, null if it's empty.
: ?number
Mth // 2Mth // null
Mth.minBy
Returns the last item in collection for which valueFn returns the smallest number, null if collection is empty.
minBy<K V>collection: KeyedCollection<K V>number: ?V
Mth // 2Mth // null
Mth.max
Returns the largest of all values in collection, null if it's empty.
: ?number
Mth // 8Mth // null
Mth.maxBy
Returns the last item in collection for which valueFn returns the largest number, null if collection is empty.
maxBy<K V>collection: KeyedCollection<K V>number: ?V
Mth // 1Mth // null
Mth.mean
Returns the mean (average) of all values in collection, null if it's empty.
: ?number
Mth // 13Mth // null
Mth.median
Returns the median (middle) of all values in collection, null if it's empty.
It the collection has an even number of items, the result will be the average of the two middle values.
: ?number
Mth // 2Mth // 2.5Mth // null
Mth.product
Returns the product of all values in collection, 1 if it's empty.
: number
Mthproduct2 3 4 // 24Mthproduct // 1
Bases
Mth.fromBase
Returns an integer parsed from a valid string representation in given base, throws otherwise.
base must be an integer between 2 and 36, throws otherwise.
For bases greater than 10, characters A-Z can indicate numerals greater than 9. A can stand for 10, B for 11 and so on up to Z for numeral 35.
: number
Mth // 8Mth // throwsMth // throwsMth // throws
Mth.baseConvert
Returns a string representation in resultBase of a number parsed from a string representation in given inputBase.
inputBase and resultBase must be integers between 2 and 36, throws otherwise.
For bases greater than 10, characters A-Z can indicate numerals greater than 9. A can stand for 10, B for 11 and so on up to Z for numeral 35.
: string
Mth // '20'Mth // throwsMth // throws
Mth.toBase
Returns a string representation of number in given base.
base must be an integer between 2 and 36, throws otherwise.
For bases greater than 10, characters A-Z indicate numerals greater than 9. A stands for 10, B for 11 and so on up to Z for numeral 35.
: string
Mth // '1120'
REx (regexp)
This module provides functions for constructing RegExps.
Every RegExp consists of a string source and a string flags, which determine its behavior.
For using RegExps for matching strings use the Str module. For basic construction use JavaScript built-ins.
const pattern = /hello \w+/iconst pattern = "hello \\w+" "i"
Check
REx.equals
Returns whether given RegExps are equal.
For patterns to be equal their source and flags must be strictly equal.
: boolean
REx // true
Combine
REx.concat
Create a new RegExp by combining the sources of given patterns.
The new RegExp inherits the flags from the last given pattern.
: RegExp
REx // /ab/m
REx.append
Create a new RegExp by adding appended to the end of the source of the given pattern.
: RegExp
REx // /ab/iREx // /ab/i
REx.prepend
Create a new RegExp by adding prepended at the start of the source of the given pattern.
: RegExp
REx // /ba/iREx // /ba/i
REx.addFlags
Returns a RegExp which includes flags from pattern and given flags.
This function throws if the given flags include invalid characters.
: RegExp
REx // /a/gi
REx.removeFlags
Returns a RegExp which includes flags from pattern not present in given flags.
: RegExp
REx // /a
St (set)
This module provides functions which operate on collections (Arrays, Maps, Sets) and return read-only (immutable) Sets.
Construction
$St
Create a Set.
Can contain any JS value. Maintains uniqueness.
$St<V>...args: $Array<V>: $Set<V>
// Set {1, 2, 3}
St.from
Convert any collection of values to a Set of values.
Note that this is not a way to clone a Set, if passed a Set, the same set will be returned.
from<V>collection: Collection<V>: $Set<V>
St // $St(1, 2, 3)St // $St(1, 2, 3)
St.keys
Convert any collection with keys to a Set of keys.
Notably the keys of a Set are just its values. The keys of an Array are its indices.
keys<K>collection: KeyedCollection<K any>: $Set<K>
St // $St(0, 1)St // $St('a', 'b')St
St.fromAsync
Convert any collection of awaitable promises of values to a single promise of a Set of values.
: Promise<$Set<V>>
St // $St(1, 2)
St.mutable
Convert any collection of values to a mutable Set of values.
If a Set is given it will be cloned.
mutable<V>collection: Collection<V>: Set<V>
St // Set {1, 2, 3}
Checks
St.equals
Returns whether given Sets are equal.
All items must be strictly equal.
equals<V>set: $Set<V> ...sets: $Array<$Set<V>>: boolean
St // true
St.equalsOrderIgnored
Returns whether given Sets contain the same values.
All items must be strictly equal.
equalsOrderIgnored<V>set: $Set<V>...sets: $Array<$Set<V>>: boolean
St // true
St.equalsNested
Returns whether given Sets and any nested collections are equal.
Any contained collections must deeply equal, all other items must be strictly equal.
equalsNested<V>set: $Set<V>...sets: $Array<$Set<V>>: boolean
Ar // true
Combine
St.add
Create a Set with value added.
add<V>collection: Collection<V> value: V: $Set<V>
St // $St(1, 2, 3, 4)
St.union
Create a Set which is a union of all values in given collections.
union<V>...collections: $Array<Collection<V>>: $Set<V>
St // $St(1, 2, 3, 4, 5)
St.intersect
Create a Set which is an intersection of all values in given collections.
intersect<V>...collections: $Array<Collection<V>>: $Set<V>
St // $St(2)
St.diff
Create a Set which has the values from collection that do not appear in any of the given collections.
diff<V>collection: Collection<V>...collections: $Array<Collection<V>>: $Set<V>
St // $St(3)
St.flatten
Create a Set which is a union of all values in given collections.
flatten<V>collections: $Array<Collection<V>>: $Set<V>
St // $St(1, 2, 3, 4, 5)
Select
St.filter
Create a new Set by filtering out values for which fn returns false.
filter<K V>collection: KeyedCollection<K V>boolean: $Set<V>
St // $St(1, 3)
St.filterAsync
Create a promise of a Set by filtering out values in collection for which async fn returns false.
Executes predicateFn on all items in collection concurrently.
: Promise<$Set<V>>
St // $St(1, 3)
St.filterNulls
Create a new set by filtering out nulls and undefineds.
Here because its type is more specific then the generic filter function.
filterNulls<V>collection: Collection<?V>): $Set<V>
St // $St(1, 3)
St.filterKeys
Create a Set of keys corresponding to values passing given predicateFn.
filterKeys<K V>collection: KeyedCollection<K V>boolean: $Set<K>
St // $St('a')
Transform
St.map
Create a new set by calling given fn on each value of collection.
map<K VFrom VTo>collection: KeyedCollection<K VFrom>VTo: $Set<VTo>
St // $St(2, 4)
St.mapAsync
Create a promise of a Set by calling given async fn on each value of collection.
Executes fn on all items in collection concurrently.
: Promise<$Set<VTo>>
await St // $St(2, 4)
St.mapFlat
Create a new set by calling given fn on each value of collection and flattening the results.
Equivalent to using map followed by flatten, for simplicity and improved performance.
mapFlat<VFrom VTo>collection: Collection<VFrom>Collection<VTo>: $Set<VTo>
St // $St(0, 1, 2)
Divide
St.remove
Create a Set with value removed.
remove<V>collection: Collection<V> value: V: $Set<V>
St // $St(2, 3)St // $St(1, 2, 3)
St.chunk
Create an array of Sets which are chunks of given collection of given size.
If the collection doesn't divide evenly, the final chunk will be smaller than the rest. The collection will be first converted to a Set.
chunk<V>collection: Collection<V>size: number: $Array<$Set<V>>
St // [$St(4, 2), $St(3, 5), $St(6)]
St.partition
Create a tuple of Sets containing items of collection which match and don't match predicateFn respectively.
More effecient than using multiple St.filter calls.
partition<K V>collection: KeyedCollection<K V>boolean: $Set<V> $Set<V>
St // [$Set(2), $Set(1, 3)]
Str (string)
Work in progress
Check
Construct
Str.fromNumber
Create the string representation of number, with given number of decimals, which defaults to 0, and optionally using a different decimalPoint and adding a thousandsSeparator.
For a string represention that shows all present decimals use `String(number)`.
: string
Str // '1234'Str // '1234.6'Str // '1234.5600'Str // '1.234,56'
Str.fromNumberInLocale
Create the string representation of number based on the execution environment.
See developer.mozilla.org/.../NumberFormat for full details.
There is currently no counter part, ie no Str.toNumberFromLocale, because there is no such API in JavaScript.
: string
Str.fill
Create a new string by concatenating count results of calling fn.
fn takeFirst as the first argument the position in the final string where the current invocation's result will be placed.
: string
Str // '1234'
Checks
Str.includes
Returns whether string includes search.
If fromIndex is given then the occurence must be at or after it.
: boolean
Str // trueStr // true
Str.indexOf
Returns the index of the first occurence of search in string or null.
If fromIndex is given then the occurence must be at or after it.
: ?number
Str // 2Str // 2
Str.lastIndexOf
Returns the index of the last occurence of search in string or null.
If fromIndex is given then the occurence must be at or after it.
Str // 2
Str.ignoreCase
Returns whether given predicateFn returns true for string and search when letter casing is ignored.
: boolean
StrignoreCase"abcd" "AbCD" Strequals // trueStrignoreCase"abcd" "AbCD" Strequals // true
Select
Str.matchEvery
Returns every match corresponding to search that occurs in string.
See Str.matchFirst for the description of the values in the returned array.
: $Array<RegExp$matchResult>
Str // [['a'], ['b'], ['cd']]
Str.matchFirst
Returns the first match corresponding to search that occurs in string or null.
If a matching substring is present the result will be an array where the first element is the full matching substring followed by smaller substrings corresponding to any matching regex groups. The array will have the property index which is the index at which the match occured in string and the property groups which will contain an object mapping named regex groups to the matching substrings, or undefined if there were no named groups in search.
If search is a regex with the g flag the flag will be ignored.
: ?RegExp$matchResult
Str // ['app', 'pp'] {index: 0}
Str.slice
Returns a substring of string starting with character at position startIndex and ending before character at position endIndex or at the end of string if no endIndex is given.
Either index can be negative, in which case they are counted from the end of the string, with last character being at index `-1`.
: string
Str // 'bc'Str // 'de'
Str.takeFirst
Returns the first n characters in string.
Throws if n is negative.
: string
Str // 'abc'
Str.dropFirst
Returns the last n characters in string.
Throws if n is negative.
: string
Str // 'def'
Str.takeFirstWhile
Returns all characters from string preceding the character for which predicateFn returns false.
: string
Str // 'abc'
Str.dropFirstWhile
Returns all characters from string following and including the first character for which predicateFn returns true.
: string
Str // 'defg'
Str.trim
Returns string with whitespace stripped from the beginning and end.
If search is given it will be stripped instead from both ends. The beginning will be trimmed first.
: string
Str // 'abc'Str // 'dolly'Str // 'na'Str // '832'
Str.trimStart
Returns string with whitespace stripped from its beginning.
If prefix is given it will be stripped instead.
: string
Str // 'abc 'Str // 'dollyhello'Str // '832da'
Str.trimEnd
Returns string with whitespace stripped from its end.
If suffix is given it will be stripped instead.
: string
Str // ' abc'Str // 'hellodolly'Str // 'ya832'
Combine
Divide
Str.splitAt
Create a tuple of strings containing the first n characters and all but the first n characters of given string.
: string string
Str // ["he", "llo"]