A fast immutable list with a functional API.
List
List is a purely functional alternative to arrays. It is an
implementation of a fast persistent sequence data structure. Compared
to JavaScript's Array
List has three major benefits.
- Safety. List is immutable. This makes it safer and better suited for functional programming. It doesn't tempt you with an imperative API and accidental mutations won't be a source of bugs.
- Performance. Since List doesn't allow mutations it can be heavily optimized for pure operations. This makes List much faster for functional programming than arrays. See the benchmarks.
- API: List has a large API of useful functions and offers both chainable methods and curried functions to suit every taste.
Features
- Familiar functional API. List follows the naming conventions common in functional programming and has arguments ordered for currying/partial application.
- Extensive API. List has all the functions known from
Array
and a lot of additional functions that'll save the day once you need them. - Extremely fast. List is a carefully optimized implementation of the highly efficient data-structure relaxed radix balanced trees. We have an extensive benchmark suite to ensure optimal performance. Here is an explanation how
- Several API styles. In addition to the base API List offers additional
API styles. Import
list/methods
to get chainable methods or alterntively importlist/curried
to get a version of the API where every function is curried. Both variants are 100% TypeScript compatible. - Does one thing well. Instead of offering a wealth of data structures List has a tight focus on being the best immutable list possible. It doesn't do everything but is designed to work well with the libraries you're already using.
- Seamless Ramda integration. If you know Ramda you already know how to use List. List was designed to integrate seamlessly with Ramda.
- Type safe. List is implemented in TypeScript. It makes full use of TypeScript features to provide accurate types that covers the entire library.
- Fully compatible with tree-shaking. List ships with tree-shaking
compatible ECMAScript modules.
import * as L from "list"
in itself adds zero bytes to your bundle when using Webpack. Using a function adds only that function and the very small (<1KB) core of the library. You only pay in size for the functions that you actually use. - Iterable. Implements the JavaScript iterable protocol. This
means that lists can be use in
for..of
loops, works with destructuring, and can be passed to any function expecting an iterable. See more. - Fantasy Land support. List implements both the Fantasy Land and the Static Land specification.
Package | Version | Downloads | Dependencies | Dev Deps | Install size | GZIP size |
---|---|---|---|---|---|---|
list |
Getting started
This section explains how to get started using List. First you'll have to install the library.
npm i list
Then you can import it.
// As an ES module;// Or with requireconst L = ;
Then you can begin using List instead of arrays and enjoy immutability the performance benefits.
As a replacement for array literals List offers the function list
for constructing lists. Instead of using [...]
to construct an array
with the content ...
one can use list(...)
to construct a list
with the same content. Here is an example.
// An array literalconst myArray = 0 1 2 3;// The List equivalentconst myList = L;
List has all the common functions that you know from native arrays and other libraries.
const myList = L;myListlength; //=> 6L; //=> list(0, 2, 4)L; //=> list(0, 1, 4, 9, 16, 25)L; //=> 15L; //=> list(2, 3, 4)L; //=> list(0, 1, 2, 3, 4, 5, 6, 7, 8);
You'll probably also end up needing to convert between arrays and
List. You can do that with the functions from
and toArray
.
L; //=> ["foo", "bar"];L; //=> L.list("foo", "bar");
List offers a wealth of other useful and high-performing functions. You can see them all in the API documentation
API styles
List offers several API styles. By default the library exports "plain"
functions. Additionally curried functions can be imported from list/curried
and an API with chainable methods can be imported from list/methods
. The
differences are illustrated below.
The default export offers normal plain function.
; ;
In list/methods
all functions are available as chainable methods.
; .filterp.age > 22 .sortByp.name .take5;
In list/curried
all functions are curried. In the example below the partially
applied functions are composed together using Ramda's
pipe
. Alternatively one could have used
Lodash's flowRight
.
;; ;
Iterable
List implements the JavaScript iterable protocol. This means that lists can be used with array destructuring just like normal arrays.
const myList = L;const first second = myList;first; //=> "first"second; //=> "second"
Lists can also be used in for..of
loops.
for const element of myList console;// logs: first, second, third, fourth
And they can be passed to any function that takes an iterable as its argument.
As an example a list can be converted into a native
Set
.
const mySet = myList;mySet; //=> true
This works because the Set
constructor accepts any iterable as
argument.
Lists also work with spread syntax. For instance, you can call a function like this.
console;
Then each element of the list will be passed as an argument to console.log
.
List also suports iterating backwards over lists through the
backwards
function.
Iterator anti-patterns
The iterable protocol allows for some very convenient patterns and means that lists can integrate nicely with JavaScript syntax. But, here are two anti-patterns that you should be aware of.
- Don't overuse
for..of
loops. Functions likemap
andfoldl
are often a better choice. If you want to perform a side-effect for each element in a list you should probably useforEach
. - Don't use the spread syntax in destructuringThe syntax converts the rest of the iterable (in this case a list) into an array by iterating through the entire iterable. This is slow and it turns our list into an array. This alternative avoids both problems.const a b ...cs = myList; // Don't do thisThis uses theconst a b cs = ; // Do this
splitAt
function which splits and creates the listcs
very efficiently inO(log(n))
time.
Seamless Ramda integration
List is designed to work seamlessly together with Ramda. Ramda offers a large number of useful functions for working with arrays. List implements the same functions on its immutable data structure. This means that Ramda users can keep using the API they're familiar with. Additionally, List offers an entry point where all functions are curried.
Since List implements Ramda's array API it is very easy to convert code from using arrays to using immutable lists. As an example, consider the code below.
; R array;
The example can be converted to code using List as follows.
;; R list;
For each function operating on arrays, the R
is simply changed to an L
.
This works because List exports functions that have the same names and behavior
as Ramdas functions.
Implemented Ramda functions
The goal is to implement the entirety of Ramda's array functions for List. The list below keeps track of how many of Ramda functions that are missing and of how many that are already implemented. Currently 61 out of 76 functions have been implemented.
Implemented: adjust
, all
, any
, append
, chain
, concat
, contains
,
drop
, dropLast
, dropRepeats
, dropRepeatsWith
, dropWhile
, filter
,
find
, findIndex
, findLast
, group
, groupWith
, head
, flatten
,
indexOf
, intersperse
, init
, insert
, insertAll
, last
, lastIndexOf
,
length
, join
, map
, none
, nth
, pair
, partition
, pluck
,
prepend
, range
, reduce
, reduceRight
, reduceWhile
, reject
, remove
,
reverse
, repeat
, scan
, sequence
, slice
, sort
, splitAt
,
splitEvery
, splitWhen
, take
, takeWhile
, tail
,
takeLast
,takeLastWhile
, traverse
, times
, update
, zip
, zipWith
.
Not implemented: aperture
, dropLastWhile
, endsWith
, findLastIndex
,
indexBy
, mapAccum
, mapAccumRight
, startsWith
, transpose
, unfold
,
uniq
, uniqBy
, uniqWith
, unnest
without
, xprod
.
Differences compared to Ramda
While List tries to stay as close to Ramda's API as possible there are a few deviations to be aware of.
- List's curried functions do not support the
R.__
placeholder. Instead ofR.reduce(R.__, 0, l)
one alternative is to use an arrow function_ => L.reduce(_, 0, l)
instead. sort
andsortWith
are different compared to what they do in Ramda.L.sortWith
is equivalent toR.sort
andL.sort
sorts a list without taking a comparison function. This makes the common case of sorting a list of numbers or strings easier
Fantasy Land & Static Land
List currently implements the following Fantasy Land and Static Land specifications: Setoid, semigroup, monoid, foldable, functor, apply, applicative, chain, monad.
The following specifications have not been implemented yet: Traversable, Ord.
Since methods hinder tree-shaking the Fantasy Land methods are not included by default. In order to get them you must import it likes this:
;
API documentation
The API is organized into three parts.
- Creating lists — Functions that create lists.
- Updating lists — Functions that transform lists. That is, functions that take one or more lists as arguments and returns a new list.
- Folds — Functions that extracts values based on lists. They take one or more lists as arguments and returns something that is not a list.
Creating lists
list
Creates a list based on the arguments given.
Complexity: O(n)
Example
const l = ; // creates a list of four elementsconst l2 = ; // creates a singleton
empty
Returns an empty list.
Complexity: O(1)
Example
const emptyList = ; //=> list()
of
Takes a single arguments and returns a singleton list that contains it.
Complexity: O(1)
Example
of"foo"; //=> list("foo")
pair
Takes two arguments and returns a list that contains them.
Complexity: O(1)
Example
; //=> list("foo", "bar")
from
Converts an array, an array-like or an itearble into a list.
Complexity: O(n)
Example
; //=> list(0, 1, 2, 3, 4)
range
Returns a list of numbers between an inclusive lower bound and an exclusive upper bound.
Complexity: O(n)
Example
; //=> list(3, 4, 5, 6, 7)
repeat
Returns a list of a given length that contains the specified value in all positions.
Complexity: O(n)
Example
; //=> list(1, 1, 1, 1, 1, 1, 1); //=> list("foo", "foo", "foo")
times
Returns a list of given length that contains the value of the given function called with current index.
Complexity: O(n)
Example
const twoFirsOdds = ;const dots = ;
Updating lists
concat
Concatenates two lists.
Complexity: O(log(n))
Example
; //=> list(0, 1, 2, 3, 4)
flatten
Flattens a list of lists into a list. Note that this function does not flatten recursively. It removes one level of nesting only.
Complexity: O(n * log(m))
where n
is the length of the outer
list and m
the length of the inner lists.
Example
const nested = ;; //=> list(0, 1, 2, 3, 4, 5, 6)
prepend
Prepends an element to the front of a list and returns the new list.
Complexity: O(log(n))
, practically constant
Example
const newList = ; //=> list(0, 1, 2, 3)
append
Appends an element to the end of a list and returns the new list.
Complexity: O(log(n))
, practically constant
Example
const newList = ; //=> list(0, 1, 2, 3)
intersperse
Inserts a separator between each element in a list.
Example
; //=> list("ba", "n", "a", "n", "a")
map
Applies a function to each element in the given list and returns a new list of the values that the function return.
Complexity: O(n)
Example
; //=> list(0, 1, 4, 9, 16)
pluck
Extracts the specified property from each object in the list.
Example
const l = ;; //=> list(0, 1, 2)
update
Returns a list that has the entry specified by the index replaced with the given value.
If the index is out of bounds the given list is returned unchanged.
Complexity: O(log(n))
Example
; //=> list("a", "b", "X", "d", "e")
adjust
Returns a list that has the entry specified by the index replaced with the value returned by applying the function to the value.
If the index is out of bounds the given list is returned unchanged.
Complexity: O(log(n))
Example
; //=> list(0, 1, 3, 3, 4, 5)
slice
Returns a slice of a list. Elements are removed from the beginning and end. Both the indices can be negative in which case they will count from the right end of the list.
Complexity: O(log(n))
Example
const l = ;; //=> list(1, 2, 3); //=> list(2, 3)
take
Takes the first n
elements from a list and returns them in a new list.
Complexity: O(log(n))
Example
; //=> list(0, 1, 2)
takeWhile
Takes the first elements in the list for which the predicate returns
true
.
Complexity: O(k + log(n))
where k
is the number of elements
satisfying the predicate.
Example
; //=> list(0, 1, 2, 3); //=> list()
takeLast
Takes the last n
elements from a list and returns them in a new
list.
Complexity: O(log(n))
Example
; //=> list(3, 4, 5)
takeLastWhile
Takes the last elements in the list for which the predicate returns
true
.
Complexity: O(k + log(n))
where k
is the number of elements
satisfying the predicate.
Example
; //=> list(3, 4, 5); //=> list()
splitAt
Splits a list at the given index and return the two sides in a pair. The left side will contain all elements before but not including the element at the given index. The right side contains the element at the index and all elements after it.
Complexity: O(log(n))
Example
const l = ;; //=> [list(0, 1, 2, 3), list(4, 5, 6, 7, 8)]
splitWhen
Splits a list at the first element in the list for which the given
predicate returns true
.
Complexity: O(n)
Example
const l = ;; //=> [list(0, 1, 2, 3), list(4, 5, 6, 7)]
remove
Takes an index, a number of elements to remove and a list. Returns a new list with the given amount of elements removed from the specified index.
Complexity: O(log(n))
Example
const l = ;; //=> list(0, 1, 2, 3, 7, 8); //=> list(0, 1, 7, 8)
drop
Returns a new list without the first n
elements.
Complexity: O(log(n))
Example
; //=> list(2, 3, 4, 5)
dropWhile
Removes the first elements in the list for which the predicate returns
true
.
Complexity: O(k + log(n))
where k
is the number of elements
satisfying the predicate.
Example
; //=> list(4, 5, 6)
dropLast
Returns a new list without the last n
elements.
Complexity: O(log(n))
Example
; //=> list(0, 1, 2, 3)
dropRepeats
Returns a new list without repeated elements.
Complexity: O(n)
Example
; //=> list(0, 1, 2, 3, 4)
dropRepeatsWith
Returns a new list without repeated elements by using the given function to determine when elements are equal.
Complexity: O(n)
Example
; //=> list(0, 1, 2, 3, 4)
tail
Returns a new list with the first element removed. If the list is empty the empty list is returne.
Complexity: O(1)
Example
; //=> list(1, 2, 3); //=> list()
pop
Returns a new list with the last element removed. If the list is empty the empty list is returned.
Aliases: init
Complexity: O(1)
Example
; //=> list(0, 1, 2)
filter
Returns a new list that only contains the elements of the original
list for which the predicate returns true
.
Complexity: O(n)
Example
; //=> list(0, 2, 4, 6)
reject
Returns a new list that only contains the elements of the original
list for which the predicate returns false
.
Complexity: O(n)
Example
; //=> list(1, 3, 5)
reverse
Reverses a list.
Complexity: O(n)
Example
; //=> list(5, 4, 3, 2, 1, 0)
ap
Applies a list of functions to a list of values.
Example
; //=> list(3, 4, 5, 2, 4, 6, 1, 4, 9)
chain
Maps a function over a list and concatenates all the resulting lists together.
Also known as flatMap
.
Example
; //=> list(1, 2, 1, 2, 4, 4, 3, 6, 9)
partition
Splits the list into two lists. One list that contains all the values
for which the predicate returns true
and one containing the values for
which it returns false
.
Complexity: O(n)
Example
; //=> list(list(0, 2, 4), list(1, 3, 5))
insert
Inserts the given element at the given index in the list.
Complexity: O(log(n))
Example
; //=> list("a", "b", "c", "d", "e")
insertAll
Inserts the given list of elements at the given index in the list.
Complexity: O(log(n))
Example
; //=> list("a", "b", "c", "d", "e", "f")
zipWith
This is like mapping over two lists at the same time. The two lists are iterated over in parallel and each pair of elements is passed to the function. The returned values are assembled into a new list.
The shortest list determine the size of the result.
Complexity: O(log(n))
where n
is the length of the smallest list.
Example
const names = ;const years = ;;//=> list({ name: "Turing", year: 1912 }, { name: "Curry", year: 1900 });
zip
Iterate over two lists in parallel and collect the pairs.
Complexity: O(log(n))
where n
is the length of the smallest list.
Example
const names = ;const years = ;//=> list(["a", 0], ["b", 1], ["c", 2], ["d", 3], ["e", 4]);
sort
Sorts the given list. The list should contain values that can be compared using
the <
operator or values that implement the Fantasy Land
Ord specification.
Performs a stable sort.
Complexity: O(n * log(n))
Example
; //=> list(1, 2, 3, 5, 8)
sortBy
Sort the given list by passing each value through the function and comparing
the resulting value. The function should either return values comparable using
<
or values that implement the Fantasy Land
Ord specification.
Performs a stable sort.
Complexity: O(n * log(n))
Example
;//=> list({ n: 1, m: "baz" }, { n: 3, m: "bar" }, { n: 4, m: "foo" }) ;//=> list("z", "ba", "aa", "foo", "bar", "list")
sortWith
Sort the given list by comparing values using the given function. The function
receieves two values and should return -1
if the first value is stricty
larger than the second, 0
is they are equal and 1
if the first values is
strictly smaller than the second.
Note that the comparison function is equivalent to the one required by
Array.prototype.sort
.
Performs a stable sort.
Complexity: O(n * log(n))
Example
; //=> list(1, 2, 3, 5, 8)
group
Returns a list of lists where each sublist's elements are all equal.
Complexity: O(n)
Example
; //=> list(list(0, 0), list(1), list(2, 2, 2), list(3, 3))
groupWith
Returns a list of lists where each sublist's elements are pairwise equal based on the given comparison function.
Note that only adjacent elements are compared for equality. If all equal elements should be grouped together the list should be sorted before grouping.
Complexity: O(n)
Example
const floorEqual = Math === Math;;//=> list(list(1.1, 1.3), list(1.8, 2, 2.2), list(3.3, 3.4)) const sameLength = alength === blength;;//=> list(list("foo", "bar"), list("ab", "bc"), list("baz))
Folds
isList
Returns true
if the given argument is a list.
Complexity: O(1)
Example
; //=> false; //=> false; //=> false; //=> true
equals
Returns true if the two lists are equivalent.
Complexity: O(n)
Example
; //=> true; //=> false
equalsWith
Returns true
if the two lists are equivalent when comparing each
pair of elements with the given comparison function.
Complexity: O(n)
Example
; //=> true
toArray
Converts a list into an array.
Complexity: O(n)
Example
; //=> [0, 1, 2, 3, 4]
backwards
Returns an iterable that iterates backwards over the given list.
Complexity: O(1)
Example
const l = for const n of if l < 2 break; console;// => logs 4, 3, and then 2
nth
Gets the n
th element of the list. If n
is out of bounds
undefined
is returned.
Complexity: O(log(n))
, practically constant
Example
const l = ;; //=> 2
length
Returns the length of a list. I.e. the number of elements that it contains.
Complexity: O(1)
Example
; //=> 4
first
Returns the first element of the list. If the list is empty the
function returns undefined
.
Aliases: head
Complexity: O(1)
Example
; //=> 0; //=> undefined
last
Returns the last element of the list. If the list is empty the
function returns undefined
.
Complexity: O(1)
Example
; //=> 3; //=> undefined
foldl
Folds a function over a list. Left-associative.
Aliases: reduce
Complexity: O(n)
Example
;1 - 2 - 3 - 4 - 5; //=> -13
foldr
Folds a function over a list. Right-associative.
Aliases: reduceRight
Complexity: O(n)
Example
;1 - 2 - 3 - 4 - 5; //=> 3
foldlWhile
Similar to foldl
. But, for each element it calls the predicate function
before the folding function and stops folding if it returns false
.
Aliases: reduceWhile
Complexity: O(n)
Example
const isOdd = x % 2 === 1; const xs = L; //=> 9 const ys = L; //=> 111
scan
Folds a function over a list from left to right while collecting all the intermediate steps in a resulting list.
Complexity: O(n)
Example
const l = ;L; //=> list(0, 1, 4, 9, 13, 15));L; //=> list("", "1", "13", "135", "1354", "13542")
traverse
Map each element of list to an applicative, evaluate these applicatives from left to right, and collect the results.
This works with Fantasy Land applicatives.
Complexity: O(n)
Example
const safeDiv = d === 0 ? nothing : L; //=> just(list(5, 2.5, 2))L; //=> nothing
sequence
Evaluate each applicative in the list from left to right, and collect the results.
Complexity: O(n)
Example
L; //=> just(list(1, 2, 3))L; //=> nothing
forEach
Invokes a given callback for each element in the list from left to
right. Returns undefined
.
This function is very similar to map
. It should be used instead of
map
when the mapping function has side-effects. Whereas map
constructs a new list forEach
merely returns undefined
. This makes
forEach
faster when the new list is unneeded.
Complexity: O(n)
Example
const l = ;;//=> 0//=> 1//=> 2
every
Returns true
if and only if the predicate function returns true
for all elements in the given list.
Aliases: all
Complexity: O(n)
Example
const isEven = n % 2 === 0;; //=> true; //=> true; //=> false; //=> false
some
Returns true
if and only if there exists an element in the list for
which the predicate returns true
.
Aliases: any
Complexity: O(n)
Example
const isEven = n % 2 === 0;; //=> false; //=> true; //=> true; //=> false
indexOf
Returns the index of the first element in the list that is equal to
the given element. If no such element is found -1
is returned.
Complexity: O(n)
Example
const l = ;; //=> 0; //=> 3; //=> -1
lastIndexOf
Returns the index of the last element in the list that is equal to
the given element. If no such element is found -1
is returned.
Complexity: O(n)
Example
const l = L;L; //=> 6L; //=> 5L; //=> 0
find
Returns the first element for which the predicate returns true
. If
no such element is found the function returns undefined
.
Complexity: O(n)
Example
; //=> 6; //=> undefined
findLast
Returns the last element for which the predicate returns true
. If
no such element is found the function returns undefined
.
Complexity: O(n)
Example
; //=> 8; //=> undefined
findIndex
Returns the index of the first element for which the predicate returns
true
. If no such element is found the function returns -1
.
Complexity: O(n)
Example
; //=> 3; //=> -1
none
Returns true
if and only if the predicate function returns false
for all elements in the given list.
Complexity: O(n)
Example
const isEven = n % 2 === 0;; //=> true; //=> false; //=> false; //=> true
includes
Returns true
if the list contains the specified element. Otherwise
it returns false
.
Aliases: contains
Complexity: O(n)
Example
; //=> true; //=> false
join
Concats the strings in a list separated by a specified separator.
Complexity: O(n)
Example
; //=> "one, two, three"
Benchmarks
The benchmarks are located in the bench
directory.