Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

🐆 An immutable list with unmatched performance and a comprehensive functional API.

License

NotificationsYou must be signed in to change notification settings

funkia/list

Repository files navigation

List logo

A fast immutable list with a functional API.

GitterBuild Statuscodecov

List

List is a purely functional alternative to arrays. It is animplementation of a fast persistent sequence data structure. Comparedto JavaScript'sArray List has three major benefits.

  • Safety. List is immutable. This makes it safer and better suitedfor functional programming. It doesn't tempt you with an imperative API andaccidental mutations won't be a source of bugs.
  • Performance. Since List doesn't allow mutations it can beheavily optimized for pure operations. This makes List much faster forfunctional programming than arrays.See thebenchmarks.
  • API: List has a large API of useful functions and offers both chainablemethods and curried functions to suit every taste.

Features

  • Familiar functional API. List follows the naming conventionscommon in functional programming and has arguments ordered forcurrying/partial application.
  • Extensive API. List has all the functions known fromArrayand a lot of additional functions that'll save the day once you need them.
  • Extremely fast. List is a carefully optimized implementation ofthe highly efficient data-structurerelaxed radix balanced trees. We haveanextensive benchmark suite toensure optimal performance. Here is an explanationhow
  • Several API styles. In addition to the base API List offersadditionalAPI styles. Importlist/methods to get chainable methods oralterntively importlist/curried to get a version of the API where everyfunction is curried. Both variants are 100% TypeScript compatible.
  • Does one thing well. Instead of offering a wealth of datastructures 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 librariesyou're already using.
  • Seamless Ramda integration. If you know Ramda you already knowhow to use List. List was designed to integrateseamlessly withRamda.
  • Type safe. List is implemented in TypeScript. It makes full use ofTypeScript features to provide accurate types that covers the entire library.
  • Fully compatible with tree-shaking. List ships with tree-shakingcompatible ECMAScript modules.import * as L from "list" in itself addszero bytes to your bundle when using Webpack. Using a function adds only thatfunction and the very small (<1KB) core of the library. You only pay in sizefor the functions that you actually use.
  • Iterable. Implements the JavaScript iterable protocol. Thismeans that lists can be use infor..of loops, works with destructuring, andcan be passed to any function expecting an iterable.See more.
  • Fantasy Land support. Listimplements both the Fantasy Land and the StaticLand specification.
PackageVersionDownloadsDependenciesDev DepsInstall sizeGZIP size
listnpm versionDownloadsDependency StatusdevDependency Statusinstall sizegzip size

Getting started

This section explains how to get started using List. First you'll haveto install the library.

npm i list

Then you can import it.

// As an ES moduleimport*asLfrom"list";// Or with requireconstL=require("list");

Then you can begin using List instead of arrays and enjoy immutabilitythe performance benefits.

As a replacement for array literals List offers the functionlistfor constructing lists. Instead of using[...] to construct an arraywith the content... one can uselist(...) to construct a listwith the same content. Here is an example.

// An array literalconstmyArray=[0,1,2,3];// The List equivalentconstmyList=L.list(0,1,2,3);

List has all the common functions that you know from native arrays andother libraries.

constmyList=L.list(0,1,2,3,4,5);myList.length;//=> 6L.filter(isEven,myList);//=> list(0, 2, 4)L.map(n=>n*n,myList);//=> list(0, 1, 4, 9, 16, 25)L.reduce((sum,n)=>sum+n,0,myList);//=> 15L.slice(2,5,myList);//=> list(2, 3, 4)L.concat(myList,L.list(6,7,8));//=> list(0, 1, 2, 3, 4, 5, 6, 7, 8);

You'll probably also end up needing to convert between arrays andList. You can do that with the functionsfrom andtoArray.

L.toArray(L.list("foo","bar"));//=> ["foo", "bar"];L.from(["foo","bar"]);//=> L.list("foo", "bar");

List offers a wealth of other useful and high-performing functions.You can see them all in theAPI documentation

API styles

List offers several API styles. By default the library exports "plain"functions. Additionally curried functions can be imported fromlist/curriedand an API with chainable methods can be imported fromlist/methods. Thedifferences are illustrated below.

The default export offers normal plain function.

import*asLfrom"list";constl=L.take(5,L.sortBy(p=>p.name,L.filter(p=>p.age>22,people)));

Inlist/methods all functions are available as chainable methods.

import*asLfrom"list/methods";constl=people.filter(p=>p.age>22).sortBy(p=>p.name).take(5);

Inlist/curried all functions are curried. In the example below the partiallyapplied functions are composed together using Ramda'spipe. Alternatively one could have usedLodash'sflowRight.

import*asRfrom"ramda";import*asLfrom"list/curried";constl=R.pipe(L.filter(p=>p.age>22),L.sortBy(p=>p.name),L.take(5))(people);

Iterable

List implements the JavaScript iterable protocol. This means thatlists can be used with array destructuring just like normal arrays.

constmyList=L.list("first","second","third","fourth");const[first,second]=myList;first;//=> "first"second;//=> "second"

Lists can also be used infor..of loops.

for(constelementofmyList){console.log(element);}// 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 nativeSet.

constmySet=newSet(myList);mySet.has("third");//=> true

This works because theSet constructor accepts any iterable asargument.

Lists also work withspreadsyntax.For instance, you can call a function like this.

console.log(...list("hello","there","i'm","logging","elements"));

Then each element of the list will be passed as an argument toconsole.log.

List also suports iterating backwards over lists through thebackwards function.

Iterator anti-patterns

The iterable protocol allows for some very convenient patterns andmeans that lists can integrate nicely with JavaScript syntax. But,here are two anti-patterns that you should be aware of.

  1. Don't overusefor..of loops. Functions likemap andfoldl are often a better choice. If you want to performa side-effect for each element in a list you should probably useforEach.
  2. Don't use the spread syntax in destructuring
    const[a,b, ...cs]=myList;// Don't do this
    The syntax converts the rest of the iterable (in this case a list)into an array by iterating through the entire iterable. This isslow and it turns our list into an array. This alternative avoidsboth problems.
    const[[a,b],cs]=splitAt(2,myList);// Do this
    This uses thesplitAt function which splits andcreates the listcs very efficiently inO(log(n)) time.

Seamless Ramda integration

List is designed to work seamlessly together with Ramda. Ramda offers a largenumber of useful functions for working with arrays. List implements the samefunctions on its immutable data structure. This means that Ramda users can keepusing the API they're familiar with. Additionally, List offers an entry pointwhere all functions are curried.

Since List implements Ramda's array API it is very easy to convert code fromusing arrays to using immutable lists. As an example, consider the code below.

import*asRfrom"ramda";R.pipe(R.filter(n=>n%2===0),R.map(R.multiply(3)),R.reduce(R.add,0))(array);

The example can be converted to code using List as follows.

import*asRfrom"ramda";import*asLfrom"list/curried";R.pipe(L.filter(n=>n%2===0),L.map(R.multiply(3)),L.reduce(R.add,0))(list);

For each function operating on arrays, theR is simply changed to anL.This works because List exports functions that have the same names and behavioras Ramdas functions.

Implemented Ramda functions

The goal is to implement the entirety of Ramda's array functions forList. The list below keeps track of how many of Ramda functions thatare missing and of how many that are already implemented. Currently 61out 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,unnestwithout,xprod.

Differences compared to Ramda

While List tries to stay as close to Ramda's API as possible there are a fewdeviations to be aware of.

  • List's curried functions do not support theR.__ 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 whatthey do in Ramda.L.sortWith is equivalent toR.sort andL.sort sorts alist without taking a comparison function. This makes the common case ofsorting a list of numbers or strings easier

Fantasy Land & Static Land

Fantasy Land

List currently implements the following Fantasy Land and Static Landspecifications: 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 notincluded by default. In order to get them you must import it likesthis:

import"list/fantasy-land";

API documentation

The API is organized into three parts.

  1. Creating lists — Functions thatcreate lists.
  2. Updating lists — Functions thattransform lists.That is, functions that take one or more lists as arguments andreturns a new list.
  3. Folds — Functions thatextracts values based on lists.They take one or more lists as arguments and returns something thatis not a list.

Creating lists

list

Creates a list based on the arguments given.

Complexity:O(n)

Example

constl=list(1,2,3,4);// creates a list of four elementsconstl2=list("foo");// creates a singleton

empty

Returns an empty list.

Complexity:O(1)

Example

constemptyList=empty();//=> 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

pair("foo","bar");//=> list("foo", "bar")

from

Converts an array, an array-like or an itearble into a list.

Complexity:O(n)

Example

from([0,1,2,3,4]);//=> list(0, 1, 2, 3, 4)

range

Returns a list of numbers between an inclusive lower bound and anexclusive upper bound.

Complexity:O(n)

Example

range(3,8);//=> list(3, 4, 5, 6, 7)

repeat

Returns a list of a given length that contains the specified value inall positions.

Complexity:O(n)

Example

repeat(1,7);//=> list(1, 1, 1, 1, 1, 1, 1)repeat("foo",3);//=> 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

consttwoFirsOdds=times(i=>i*2+1,2);constdots=times(()=>{constx=Math.random()*width;consty=Math.random()*height;return{ x, y};},50);

Updating lists

concat

Concatenates two lists.

Complexity:O(log(n))

Example

concat(list(0,1,2),list(3,4));//=> list(0, 1, 2, 3, 4)

flatten

Flattens a list of lists into a list. Note that this function doesnot flatten recursively. It removes one level of nesting only.

Complexity:O(n * log(m)) wheren is the length of the outerlist andm the length of the inner lists.

Example

constnested=list(list(0,1,2,3),list(4),empty(),list(5,6));flatten(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

constnewList=prepend(0,list(1,2,3));//=> 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

constnewList=append(3,list(0,1,2));//=> list(0, 1, 2, 3)

intersperse

Inserts a separator between each element in a list.

Example

intersperse("n",list("ba","a","a"));//=> list("ba", "n", "a", "n", "a")

map

Applies a function to each element in the given list and returns a newlist of the values that the function return.

Complexity:O(n)

Example

map(n=>n*n,list(0,1,2,3,4));//=> list(0, 1, 4, 9, 16)

pluck

Extracts the specified property from each object in the list.

Example

constl=list({foo:0,bar:"a"},{foo:1,bar:"b"},{foo:2,bar:"c"});pluck("foo",l);//=> list(0, 1, 2)

update

Returns a list that has the entry specified by the index replaced withthe given value.

If the index is out of bounds the given list isreturned unchanged.

Complexity:O(log(n))

Example

update(2,"X",list("a","b","c","d","e"));//=> list("a", "b", "X", "d", "e")

adjust

Returns a list that has the entry specified by the index replaced withthe value returned by applying the function to the value.

If the index is out of bounds the given list isreturned unchanged.

Complexity:O(log(n))

Example

adjust(2,inc,list(0,1,2,3,4,5));//=> list(0, 1, 3, 3, 4, 5)

slice

Returns a slice of a list. Elements are removed from the beginning andend. Both the indices can be negative in which case they will countfrom the right end of the list.

Complexity:O(log(n))

Example

constl=list(0,1,2,3,4,5);slice(1,4,l);//=> list(1, 2, 3)slice(2,-2,l);//=> list(2, 3)

take

Takes the firstn elements from a list and returns them in a new list.

Complexity:O(log(n))

Example

take(3,list(0,1,2,3,4,5));//=> list(0, 1, 2)

takeWhile

Takes the first elements in the list for which the predicate returnstrue.

Complexity:O(k + log(n)) wherek is the number of elementssatisfying the predicate.

Example

takeWhile(n=>n<4,list(0,1,2,3,4,5,6));//=> list(0, 1, 2, 3)takeWhile(_=>false,list(0,1,2,3,4,5));//=> list()

takeLast

Takes the lastn elements from a list and returns them in a newlist.

Complexity:O(log(n))

Example

takeLast(3,list(0,1,2,3,4,5));//=> list(3, 4, 5)

takeLastWhile

Takes the last elements in the list for which the predicate returnstrue.

Complexity:O(k + log(n)) wherek is the number of elementssatisfying the predicate.

Example

takeLastWhile(n=>n>2,list(0,1,2,3,4,5));//=> list(3, 4, 5)takeLastWhile(_=>false,list(0,1,2,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 theelement at the given index. The right side contains the element at theindex and all elements after it.

Complexity:O(log(n))

Example

constl=list(0,1,2,3,4,5,6,7,8);splitAt(4,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 givenpredicate returnstrue.

Complexity:O(n)

Example

constl=list(0,1,2,3,4,5,6,7);splitWhen((n)=>n>3,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 anew list with the given amount of elements removed from the specifiedindex.

Complexity:O(log(n))

Example

constl=list(0,1,2,3,4,5,6,7,8);remove(4,3,l);//=> list(0, 1, 2, 3, 7, 8)remove(2,5,l);//=> list(0, 1, 7, 8)

drop

Returns a new list without the firstn elements.

Complexity:O(log(n))

Example

drop(2,list(0,1,2,3,4,5));//=> list(2, 3, 4, 5)

dropWhile

Removes the first elements in the list for which the predicate returnstrue.

Complexity:O(k + log(n)) wherek is the number of elementssatisfying the predicate.

Example

dropWhile(n=>n<4,list(0,1,2,3,4,5,6));//=> list(4, 5, 6)

dropLast

Returns a new list without the lastn elements.

Complexity:O(log(n))

Example

dropLast(2,list(0,1,2,3,4,5));//=> list(0, 1, 2, 3)

dropRepeats

Returns a new list without repeated elements.

Complexity:O(n)

Example

dropRepeats(L.list(0,0,1,1,1,2,3,3,4,4));//=> list(0, 1, 2, 3, 4)

dropRepeatsWith

Returns a new list without repeated elements by using the givenfunction to determine when elements are equal.

Complexity:O(n)

Example

dropRepeatsWith((n,m)=>Math.floor(n)===Math.floor(m),list(0,0.4,1.2,1.1,1.8,2.2,3.8,3.4,4.7,4.2));//=> list(0, 1, 2, 3, 4)

tail

Returns a new list with the first element removed. If the list isempty the empty list is returne.

Complexity:O(1)

Example

tail(list(0,1,2,3));//=> list(1, 2, 3)tail(empty());//=> list()

pop

Returns a new list with the last element removed. If the list is emptythe empty list is returned.

Aliases:init

Complexity:O(1)

Example

pop(list(0,1,2,3));//=> list(0, 1, 2)

filter

Returns a new list that only contains the elements of the originallist for which the predicate returnstrue.

Complexity:O(n)

Example

filter(isEven,list(0,1,2,3,4,5,6));//=> list(0, 2, 4, 6)

reject

Returns a new list that only contains the elements of the originallist for which the predicate returnsfalse.

Complexity:O(n)

Example

reject(isEven,list(0,1,2,3,4,5,6));//=> list(1, 3, 5)

reverse

Reverses a list.

Complexity:O(n)

Example

reverse(list(0,1,2,3,4,5));//=> list(5, 4, 3, 2, 1, 0)

ap

Applies a list of functions to a list of values.

Example

ap(list((n:number)=>n+2,n=>2*n,n=>n*n),list(1,2,3));//=> list(3, 4, 5, 2, 4, 6, 1, 4, 9)

chain

Maps a function over a list and concatenates all the resulting liststogether.

Aliases:flatMap

Example

chain(n=>list(n,2*n,n*n),list(1,2,3));//=> list(1, 2, 1, 2, 4, 4, 3, 6, 9)

partition

Splits the list into two lists. One list that contains all the valuesfor which the predicate returnstrue and one containing the values forwhich it returnsfalse.

Complexity:O(n)

Example

partition(isEven,list(0,1,2,3,4,5));//=> 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

insert(2,"c",list("a","b","d","e"));//=> 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

insertAll(2,list("c","d"),list("a","b","e","f"));//=> list("a", "b", "c", "d", "e", "f")

zipWith

This is like mapping over two lists at the same time. The two lists areiterated 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)) wheren is the length of the smallest list.

Example

constnames=list("Turing","Curry");constyears=list(1912,1900);zipWith((name,year)=>({ name, year}),names,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)) wheren is the length of the smallest list.

Example

constnames=list("a","b","c","d","e");constyears=list(0,1,2,3,4,5,6);//=> 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 usingthe< operator or values that implement the Fantasy LandOrd specification.

Performs a stable sort.

Complexity:O(n * log(n))

Example

sort(list(5,3,1,8,2));//=> list(1, 2, 3, 5, 8)sort(list("e","a","c","b","d");//=> list("a", "b", "c", "d", "e")

sortBy

Sort the given list by passing each value through the function and comparingthe resulting value. The function should either return values comparable using< or values that implement the Fantasy LandOrd specification.

Performs a stable sort.

Complexity:O(n * log(n))

Example

sortBy(o=>o.n,list({n:4,m:"foo"},{n:3,m:"bar"},{n:1,m:"baz"}));//=> list({ n: 1, m: "baz" }, { n: 3, m: "bar" }, { n: 4, m: "foo" })sortBy(s=>s.length,list("foo","bar","ba","aa","list","z"));//=> list("z", "ba", "aa", "foo", "bar", "list")

sortWith

Sort the given list by comparing values using the given function. The functionreceieves two values and should return-1 if the first value is strictylarger than the second,0 is they are equal and1 if the first values isstrictly smaller than the second.

Note that the comparison function is equivalent to the one required byArray.prototype.sort.

Performs a stable sort.

Complexity:O(n * log(n))

Example

sortWith((a,b)=>{if(a===b){return0;}elseif(a<b){return-1;}else{return1;}},list(5,3,1,8,2));//=> list(1, 2, 3, 5, 8)

group

Returns a list of lists where each sublist's elementsare all equal.

Complexity:O(n)

Example

group(list(0,0,1,2,2,2,3,3));//=> 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 pairwiseequal based on the given comparison function.

Note that only adjacent elements are compared for equality. If allequal elements should be grouped together the list should be sortedbefore grouping.

Complexity:O(n)

Example

constfloorEqual=(a,b)=>Math.round(a)===Math.round(b);groupWith(floorEqual,list(1.1,1.3,1.8,2,2.2,3.3,3.4));//=> list(list(1.1, 1.3), list(1.8, 2, 2.2), list(3.3, 3.4))constsameLength=(a,b)=>a.length===b.length;groupWith(sameLength,list("foo","bar","ab","bc","baz"));//=> list(list("foo", "bar"), list("ab", "bc"), list("baz))

Folds

isList

Returnstrue if the given argument is a list.

Complexity:O(1)

Example

isList([0,1,2]);//=> falseisList("string");//=> falseisList({foo:0,bar:1});//=> falseisList(list(0,1,2));//=> true

isEmpty

Returnstrue if the list is empty.

Complexity:O(1)

Example

isEmpty(empty());//=> trueisEmpty(list());//=> trueisEmpty(list(0,1,2));//=> false

equals

Returns true if the two lists are equivalent.

Complexity:O(n)

Example

equals(list(0,1,2,3),list(0,1,2,3));//=> trueequals(list("a","b","c"),list("a","z","c"));//=> false

equalsWith

Returnstrue if the two lists are equivalent when comparing eachpair of elements with the given comparison function.

Complexity:O(n)

Example

equalsWith((n,m)=>n.length===m.length,list("foo","hello","one"),list("bar","world","two"));//=> true

toArray

Converts a list into an array.

Complexity:O(n)

Example

toArray(list(0,1,2,3,4));//=> [0, 1, 2, 3, 4]

backwards

Returns an iterable that iterates backwards over the given list.

Complexity:O(1)

Example

constl=list(0,1,2,3,4)for(constnofbackwards(l)){if(l<2){break;}console.log(l);}// => logs 4, 3, and then 2

nth

Gets thenth element of the list. Ifn is out of boundsundefined is returned.

Complexity:O(log(n)), practically constant

Example

constl=list(0,1,2,3,4);nth(2,l);//=> 2

length

Returns the length of a list. I.e. the number of elements that itcontains.

Complexity:O(1)

Example

length(list(0,1,2,3));//=> 4

first

Returns the first element of the list. If the list is empty thefunction returnsundefined.

Aliases:head

Complexity:O(1)

Example

first(list(0,1,2,3));//=> 0first(list());//=> undefined

last

Returns the last element of the list. If the list is empty thefunction returnsundefined.

Complexity:O(1)

Example

last(list(0,1,2,3));//=> 3last(list());//=> undefined

foldl

Folds a function over a list. Left-associative.

Aliases:reduce

Complexity:O(n)

Example

foldl((n,m)=>n-m,1,list(2,3,4,5));1-2-3-4-5;//=> -13

foldr

Folds a function over a list. Right-associative.

Aliases:reduceRight

Complexity:O(n)

Example

foldr((n,m)=>n-m,5,list(1,2,3,4));1-(2-(3-(4-5)));//=> 3

foldlWhile

Similar tofoldl. But, for each element it calls the predicate functionbefore the folding function and stops folding if it returnsfalse.

Aliases:reduceWhile

Complexity:O(n)

Example

constisOdd=(_acc:,x)=>x%2===1;constxs=L.list(1,3,5,60,777,800);foldlWhile(isOdd,(n,m)=>n+m,0,xs)//=> 9constys=L.list(2,4,6);foldlWhile(isOdd,(n,m)=>n+m,111,ys)//=> 111

scan

Folds a function over a list from left to right while collecting all theintermediate steps in a resulting list.

Complexity:O(n)

Example

constl=list(1,3,5,4,2);L.scan((n,m)=>n+m,0,l);//=> list(0, 1, 4, 9, 13, 15));L.scan((s,m)=>s+m.toString(),"",l);//=> list("", "1", "13", "135", "1354", "13542")

traverse

Map each element of list to an applicative, evaluate theseapplicatives from left to right, and collect the results.

This works with Fantasy Landapplicatives.

Complexity:O(n)

Example

constsafeDiv=n=>d=>d===0 ?nothing :just(n/d)L.traverse(Maybe,safeDiv(10),list(2,4,5));//=> just(list(5, 2.5, 2))L.traverse(Maybe,safeDiv(10),list(2,0,5));//=> nothing

sequence

Evaluate each applicative in the list from left to right, andcollect the results.

Complexity:O(n)

Example

L.sequence(Maybe,list(just(1),just(2),just(3)));//=> just(list(1, 2, 3))L.sequence(Maybe,list(just(1),just(2),nothing()));//=> nothing

forEach

Invokes a given callback for each element in the list from left toright. Returnsundefined.

This function is very similar tomap. It should be used instead ofmap when the mapping function has side-effects. Whereasmapconstructs a new listforEach merely returnsundefined. This makesforEach faster when the new list is unneeded.

Complexity:O(n)

Example

constl=list(0,1,2);forEach(element=>console.log(element));//=> 0//=> 1//=> 2

every

Returnstrue if and only if the predicate function returnstruefor all elements in the given list.

Aliases:all

Complexity:O(n)

Example

constisEven=n=>n%2===0;every(isEven,empty());//=> trueevery(isEven,list(2,4,6,8));//=> trueevery(isEven,list(2,3,4,6,7,8));//=> falseevery(isEven,list(1,3,5,7));//=> false

some

Returnstrue if and only if there exists an element in the list forwhich the predicate returnstrue.

Aliases:any

Complexity:O(n)

Example

constisEven=n=>n%2===0;some(isEven,empty());//=> falsesome(isEven,list(2,4,6,8));//=> truesome(isEven,list(2,3,4,6,7,8));//=> truesome(isEven,list(1,3,5,7));//=> false

indexOf

Returns the index of thefirst element in the list that is equal tothe given element. If no such element is found-1 is returned.

Complexity:O(n)

Example

constl=list(12,4,2,89,6,18,7);indexOf(12,l);//=> 0indexOf(89,l);//=> 3indexOf(10,l);//=> -1

lastIndexOf

Returns the index of thelast element in the list that is equal tothe given element. If no such element is found-1 is returned.

Complexity:O(n)

Example

constl=L.list(12,4,2,18,89,2,18,7);L.lastIndexOf(18,l);//=> 6L.lastIndexOf(2,l);//=> 5L.lastIndexOf(12,l);//=> 0

find

Returns thefirst element for which the predicate returnstrue. Ifno such element is found the function returnsundefined.

Complexity:O(n)

Example

find(isEven,list(1,3,5,6,7,9,10));//=> 6find(isEven,list(1,3,5,7,9));//=> undefined

findLast

Returns thelast element for which the predicate returnstrue. Ifno such element is found the function returnsundefined.

Complexity:O(n)

Example

findLast(isEven,list(1,3,5,6,7,8,9));//=> 8findLast(isEven,list(1,3,5,7,9));//=> undefined

findIndex

Returns the index of the first element for which the predicate returnstrue. If no such element is found the function returns-1.

Complexity:O(n)

Example

findIndex(isEven,list(1,3,5,6,7,9,10));//=> 3findIndex(isEven,list(1,3,5,7,9));//=> -1

none

Returnstrue if and only if the predicate function returnsfalsefor all elements in the given list.

Complexity:O(n)

Example

constisEven=n=>n%2===0;none(isEven,empty());//=> truenone(isEven,list(2,4,6,8));//=> falsenone(isEven,list(2,3,4,6,7,8));//=> falsenone(isEven,list(1,3,5,7));//=> true

includes

Returnstrue if the list contains the specified element. Otherwiseit returnsfalse.

Aliases:contains

Complexity:O(n)

Example

includes(3,list(0,1,2,3,4,5));//=> trueincludes(3,list(0,1,2,4,5));//=> false

join

Concats the strings in a list separated by a specified separator.

Complexity:O(n)

Example

join(", ",list("one","two","three"));//=> "one, two, three"

Benchmarks

The benchmarks are located in thebench directory.


[8]ページ先頭

©2009-2025 Movatter.jp