add

Number -> Number -> Number

Returns the sum of two numbers.

add(1, 2) // => 3

const add5 = add(5)
add5(10) // => 15
add5(15) // => 20

all

(a -> Boolean) -> [a] -> Boolean

Tests a predicate against all items in a list. Returns true if the predicate returns true for all items in the list, otherwise returns false. If the list is empty it will return true (vacuous truth).

all(isEven, [2, 4, 6, 8])  // => true
all(isEven, [2, 4, 6, 3])  // => false, 3 is not an even number
all(isEven, [])            // => true

always

a -> (Any...) -> a

Takes a single argument and returns a function that, when invoked, always returns that original argument.

const alwaysTrue = always(true) // => function
alwaysTrue()         // => true
alwaysTrue(false)    // => true
times(alwaysTrue, 5) // => [true, true, true, true, true]

any

(a -> Boolean) -> [a] -> Boolean

Tests a predicate against all items in a list. Returns true if the predicate returns true for any item, otherwise returns false. Short circuits once a true condition is found. If the list is empty it will return false.

any(isEven, [1, 2, 3, 4, 5]) // => true, 2 is an even number
any(isEven, [1, 3, 5])       // => false, no numbers are even
any(isEven, [])              // => false

append

a -> [a] -> [a] | String -> String -> String

Appends a single element to a list. If the second argument is a string, string concatenation will be used instead.

append(4, [1, 2, 3])      // => [1, 2, 3, 4]
append([4, 5], [1, 2, 3]) // => [1, 2, 3, [4, 5]]
append('bar', 'foo')      // => 'foobar'

assoc

String k, Any v => k -> v -> {k:v} -> {k:v}

Applies a value to a given key on an object. You can think of assoc as the process of associating a key with a value.

Note that the original object is not mutated; a shallow copy is returned.

const user = { first: 'Chris', last: 'Loblaw' }
assoc('first', 'Bob', user) // => { first: 'Bob', last: 'LobLaw' }

chain

(a -> [b]) -> [a] -> [b]


compact

[a] -> [a]

Returns an array that excludes all falsy values from the original array.

compact([null, undefined, true, false]) // => [true]
compact(['', 0, {}, [], '0'])           // => [{}, [], '0']

complement

(*... -> Boolean) -> (*... -> Boolean)

Wraps a function and returns a new function, when called, invokes the original function and returns the complement of its result. For example, if the original function were to return true its complement would return false.

isEven(2) // => true
complement(isEven)(2) // => false

const isOdd = complement(isEven)
isOdd(3) // => true

compose

((y -> z), ..., (g -> h), (a, b, ..., f -> g)) -> (a, b, ..., f -> z)

Takes a series of functions and wraps them in a single, curried function that, when called, invokes the original functions from right to left, passing the result of each function call as the arguments to the next. The result of the leftmost function call is the final return value. This is the same concept as pipe, but runs the functions from right -> left. Note that all functions except for the first (rightmost) must be unary (accept only a single argument), because functions can only return a single value.

// Composes `sqrt` and `isEven` to produce a function that invokes the
// rightmost function (`sqrt`) with the arguments supplied to the composed
// function. The result of that function call is then used as the argument
// to the next function, `isEven`. Because `isEven` is the last function in
// the composition, its result is the final return value.
// This would look like: (x) => isEven(sqrt(x))
const isSqrtEven = compose(isEven, sqrt)

isSqrtEven(9)  // => false
isSqrtEven(16) // => true

// You can compose more than two functions at a time
compose(equals(4), sqrt, double)(8) // => true

concat

[a] -> [a] -> [a]

Concatenates the second array onto the first.

concat([1, 2, 3], [4, 5, 6]) // => [1, 2, 3, 4, 5, 6]
concat([1, 2, 3], [])        // => [1, 2, 3]

cond

[[(a -> Boolean), (a -> *)]] -> a -> *

Encapsulates the logic surrounding multiple if/else branches by allowing you to provide an array of tuples containing two elements, a predicate and a transform function. The resulting function will apply the arguments it receives to each predicate in turn until one is matched, at which point its paired transform function will be called with the same arguments and its result returned. If no predicate is matched undefined is returned. As a catch all, it is common to use always(true) as the last condition.

const fizzbuzz = cond([
 [x => x % 15 === 0, always('FizzBuzz')],
 [x => x % 3 === 0, always('Fizz')],
 [x => x % 5 === 0, always('Fizz')],
 [always(true), identity]
])

map(fizzbuzz, [1, 2, 3, 4, 5]) // => [1, 2, 'Fizz', 4, 'Buzz']

contains

a -> [a] -> Boolean

Returns whether or not a list contains the target value. Performs a deep equality comparison when looking up objects.

contains(1, [1, 2, 3, 4])                   // => true
contains(5, [1, 2, 3, 4])                   // => false
contains({ id: 1 }, [{ id: 1 }, { id: 2 }]) // => true

curry

(a, b, ..., j -> v) -> a -> b -> ... -> j -> v

Curries a function based on its arity, reported via its .length property. Curried functions continue to accept arguments up until the number of total arguments supplied to it meet or exceed its arity, at which point the original function is called with those arguments. If you wish to curry a function to a different or fixed arity, such as with variadic functions, use curryN.

const add = curry((a, b, c) => a + b + c)
add(5)        // => Function
add(5, 10, 2) // => 17
add(5)(2)(3)  // => 10

const add5 = add(5)
add5(3, 2) // => 10

const add7 = add(5, 2)
add7(3) // => 10

const add8 = add5(3)
add8(2) // => 10
add8(0) // => 8

curryN

Integer -> (a, b, ..., n -> v) -> a -> b -> ... -> n -> v

Curries a function to the provided arity, regardless of its actual arity.

const fn = curryN(3, (...args) => console.log(args))

fn(1)       // => Function
fn(1)(2)    // => Function
fn(1, 2, 3) // => [1, 2, 3]
fn(1)(2)(3) // => [1, 2, 3]

dec

Number -> Number

Decrements a number by 1.

dec(10) // => 9
dec(-1) // => -2

dissoc

String k, Any v => k -> {k:v} -> {k:v}

Removes a given key from an object. You can think of dissoc as the process of dissociating a key from an object. A shallow copy of the original object is always returned, regardless of whether or not the key existed.

const user = { first: 'Bob', last: 'Loblaw' }

dissoc('first', user) // => { last: 'Loblaw' }
const user = { first: 'Bob', last: 'Loblaw' }
const newUser = dissoc('age', user) // => { first: 'Bob', last: 'Loblaw' }

user === newUser // => false

divide

Number -> Number -> Number

Returns the result of the second argument divided by the first. Because infix notation with / is generally used when both arguments are known upfront, we optimize for readability with partial application.

divide(2, 8) // => 4 (divide 8 by 2)
map(divide(2), [2, 4, 6, 8]) // => [1, 2, 3, 4]

drop

Integer -> [a] -> [a]

Returns an array with the first N elements removed. If N exceeds the length of the array, an empty array will be returned.

drop(2, [1, 2, 3, 4]) // => [3, 4]
drop(5, [1, 2, 3, 4]) // => []

dropUntil

(a -> Boolean) -> [a] -> [a]

Runs a predicate function sequentially through an array, dropping all elements until the predicate returns true. Once the predicate returns true, the remainder of the array is returned.

const isEven = x => x % 2 === 0

dropUntil(isEven, [1, 3, 6, 8, 10]) // => [6, 8, 10]
dropUntil(isEven, [1, 3, 6, 5, 7])  // => [6, 5, 7]

dropWhile

(a -> Boolean) -> [a] -> [a]

Runs a predicate function sequentially through an array, dropping all elements until the predicate returns false. Once the predicate returns false, the remainder of the array is returned. This can be thought of as dropUntil(complement(predicate)).

dropWhile(isEven, [1, 2, 5, 7, 8]) // => [5, 7, 9]

empty

a -> a

Returns the empty representation of a value. Dispatches to the empty method on objects or their constructors if it exists. If the value's type does not have an applicable empty representation, undefined is returned.

empty([1, 2, 3, 4])            // => []
empty({ foo: 'bar '})          // => {}
empty('hello!')                // => ''
empty(0)                       // => undefined
empty(false)                   // => undefined
empty({ empty: () => 'FOO!' }) // => 'FOO!'

equals

a -> a -> Boolean

Deeply compares two values and returns a boolean indicating whether or not they are equal.

equals(5, 5) // => true
equals({ name: 'Bill' }, { name: 'Bill' }) // => true
equals({ name: 'Bill' }, { name: 'Bob' })  // => false

const people = [{ name: 'Bill' }, { name: 'Bob' }]
reject(equals({ name: 'Bill' }), people) // => [{ name: 'Bob' }]

filter

(a -> Boolean) -> [a] -> [a]

Filters a list by calling the predicate function with each element in the list. If the predicate returns a truthy value, the element is kept in the new array, otherwise it is discarded.

filter(isEven, [1, 2, 3, 4, 5]) // => [2, 4]

find

(a -> Boolean) -> [a] -> a | undefined

Tests a predicate against an array, returning the first value that matches that predicate. If no matching value is found, undefined is returned.

find(isEven, [1, 3, 4, 6]) // => 4
find(propEq('id', 2), [{ id: 1 }, { id : 2 }]) // => { id: 2 }
find(isEven, [1, 3, 5, 7]) // => undefined

findIndex

(a -> Boolean) -> [a] -> Number

Tests a predicate against an array, returning the index of the first vakye that matches that predicate. If no matching value is found, -1 is returned.

find(isEven, [1, 3, 4, 6]) // => 2  (4 is the first even number)
find(isEven, [1, 3, 5, 7]) // => -1

findLast

(a -> Boolean) -> [a] -> a | undefined

Finds and returns the last value in a list that matches the given predicate. If no matching value is found, undefined is returned.

const users = [{ id: 1, name: 'Bob' }, { id: 2, name: 'Bill'}, { id: 3, name: 'Bob' }]
findLast(propEq('name', 'Bob'), users) // => { id: 3, name: 'Bob' }

flatten

[[a]] -> [a]

Shallowly flattens an array (i.e. 1 level deep).

flatten([1, 2, [3, 4]])   // => [1, 2, 3, 4]
flatten([1, 2, [3, [4]]]) // => [1, 2, 3, [4]]

flattenDeep

[[a]] -> [a]

Deeply flattens an array.

flattenDeep([1, 2, [3, [4, [5, 6, [7]]]]]) // => [1, 2, 3, 4, 5, 6, 7]

flip

(a -> b -> c -> ... -> z) -> z -> ... -> c -> b -> a

Wraps a function so that when it is invoked its arguments are applied in reverse order. Note that flip produces a curried function.

const fn = flip((a, b, c) => [a, b, c])
fn('A', 'B', 'C') // => ['C', 'B', 'A']
fn('a')('b')('c') // => ['c', 'b', 'a']

fmap

Functor f => (a -> b) -> f a -> f b


forEach

(a -> *) -> [a] -> undefined

Iterates through a list, calling the provided function with each value. The result of the function call is ignored. If you wish to transform each value in the list, use map.

const log = x => console.log(x)
const res = forEach(log, [1, 2, 3]) // => logs: 1, 2, 3
console.log(res)                    // => undefined

fromPairs

[[k, v]] -> {k:v}

Builds an object out of a list of tuples containing key/value pairs. Note that for duplicate keys, the last key/value pair will be used. If you wish to merge a list of keys with a list of values, use zip or zipObj.

fromPairs([['a', 1], ['b', 2]])           // => { a: 1, b: 2 }
fromPairs([['a', 1], ['b', 2], ['a', 3]]) // => { a: 3, b: 2 }

gt

Number -> Number -> Boolean

Returns a boolean indicating whether or not the second argument was greater than the first. Because infix notation with > is generally used when both arguments are known upfront, we optimize for readability with partial application.

gt(2, 5) // => true (5 is greater than 2)
filter(gt(3), [1, 2, 3, 4, 5]) // => [4, 5]

gte

Number -> Number -> Boolean

gte(2, 5) // => true (5 is greater than 2)
gte(5, 5) // => true (5 is equal to 5)
filter(gte(3), [1, 2, 3, 4, 5]) // => [3, 4, 5]

has

String k -> {k:v} -> Boolean

Checks whether an object has the provided key as an own property.

has('name', { name: 'Bill' }) // => true

// Ignores inherited properties
class A () {
  foo () {}
}
const a = new A()
has('foo', a) // => false

[a] -> a

Returns the first element in a list. If the list is empty, undefined is returned.

head([1, 2, 3, 4]) // => [1]
head([])           // => undefined

identical

a -> a -> Boolean

Checks whether two values are strictly identical. For objects, this test asserts that they reference the same place in memory (think ===). For deep comparisons, use equals.

identical(5, 5) // => true

const a = { id: 1 }
identical(a, { id: 1 }) // => false
identical(a, a)         // => true

identity

a -> a

Unary function that returns the argument it receives. Useful for when you simply want to forward an argument along.

identity(5) // => 5

const doubleIfEven = ifElse(isEven, double, identity)
doubleIfEven(2) // => 4
doubleIfEven(3) // => 3

ifElse

(a -> Boolean) -> (a -> *) -> (a -> *) -> (a -> *)

Creates a unary function that checks its argument against a predicate and, based on that result, dispatches to either the whenTrue or whenFalse function. For example, if the predicate is met, the whenTrue function will be called and and its result returned; otherwise the whenFalse function is called. If you wish to only handle the true condition, use when.

const myFunc = ifElse(isEven, inc, dec)
myFunc(2) // => 3
myFunc(4) // => 5
myFunc(7) // => 6

inc

Number -> Number

inc(10) // => 11
inc(-1) // => 0

insert

Number -> a -> [a] -> [a]

Inserts a value at the given position in an array. This does not replace the current value, but rather shifts it and all following elements forward by one poisition.

insert(1, 5, [0, 1, 2, 3]) // => [0, 5, 1, 2, 3]

isEmpty

a -> Boolean

Returns whether or not a value is empty. To determine "emptiness", the value is compared against the empty value for its type. Dispatches to the empty method on an object if it exists.

Note that this is different from checking whether or not a value is falsy. Nil values (null and undefined) are not considered empty, nor is 0, since the concept of "emptiness" is not intuitively applicable to a number.

isEmpty('')        // => true
isEmpty([])        // => true
isEmpty({})        // => true
isEmpty(null)      // => false
isEmpty(undefined) // => false
isEmpty(0)         // => false
isEmpty(false)     // => false

isEven

Number -> Boolean

Returns whether or not a number is even.

isEven(2)        // => true
isEven(0)        // => true
isEven(2.4)      // => false
isEven(Infinity) // => false

isNil

a -> Boolean

Determines whether the argument is equal to undefined or null. This check is strictly for the above values; it does not return true for any other falsy value.

isNil(null)      // => true
isNil(undefined) // => true
isNil('')        // => false
isNil(0)         // => false

isOdd

Number -> Boolean

Returns whether or not a number is odd.

isOdd(3)        // => true
isOdd(0)        // => false
isOdd(3.9)      // => false
isOdd(Infinity) // => false

isType

(String | Function) -> Boolean

Returns whether or not a value is of an expected. If the provided type is a string, a typeof check is used. If a constructor is passed it will be compared against the value's constructor.

const isString = isType('string')

isString('hello!')    // => true
isType('number', 123) // => true

join

String -> [String] -> String

Joins all elements of an array with a given string.

join(' & ', ['Michael', 'Dwight', 'Jim']) // => 'Michael & Dwight & Jim'
join('', ['Hello', 'Goodbye'])            // => 'HelloGoodbye'

juxt

[(x, y, z... -> a), (x, y, z... -> b), ...] -> (x, y, z...) -> [a, b, ...]

Applies a set of arguments to a list of functions, returning an array that contains the result of each function call in its corresponding position.

juxt([inc, dec, multiply(3)])(2) => [3, 1, 6]
juxt([add, divide, multiply])(2, 4) => [6, 2, 8]

keys

{k:v} -> [k]

Returns an array containing all own enumerable properties of an object. Note that key order is not guaranteed due to discrepencies between JavaScript engines.

keys({ a: 1, b: 2, c: 3 }) // => ['a', 'b', 'c']

// Ignores inherited properties
class A {
  foo() {}
}
const a = new A()
keys(a) // => []
a.bar = () => {}
keys(a) // => ['bar']

last

[a] -> a

Returns the last element in an array.

last([1, 2, 3, 4]) // => 4
last([])           // => undefined

length

[a] -> Number

Returns the length of an array.

length([1, 2, 3, 4, 5]) // => 5
length([])              // => 0

lens

(({k:v} -> v), (v, {k:v} -> {k:v})) -> Lens k

Creates a Lens that knows how to get and set a specific value on an object. This lens can be used with set, over, and view in order to set, transform, and get the value at the lens' focus, respectively. If you want to create a lens focused on a specific property, you can use the convenient lensProp.

const nameLens = lens(obj => obj.name, (value, obj) => assoc('name', value, obj))
// shorthand: lens(prop('name'), assoc('name'))

view(nameLens, { name: 'Joe' })          // => Joe
set(nameLens, 'Bob', { name: 'Joe' })    // => Bob
over(nameLens, toUpper, { name: 'Joe' }) // => JOE

lensProp

String -> Lens

Creates a Lens that is focused on a given property. The getter and setter for the created lens do not mutate the target object.

const nameLens = lensProp('name')
const bob = { name: 'Bob' }

view(nameLens, bob)      // => 'Bob'
set(nameLes, 'Joe', bob) // => { name: 'Joe' }
console.log(bob)         // => { name: 'Bob' }

lt

Number -> Number -> Boolean

Returns a boolean indicating whether or not the second argument was less than the first. Because infix notation with < is generally used when both arguments are known upfront, we optimize for readability with partial application.

lt(2, 1) // => true (1 is less than 2)
filter(lt(3), [1, 2, 3, 4, 5]) // => [1, 2]

lte

Number -> Number -> Boolean

Returns a boolean indicating whether or not the second argument was less than or equal to the first. Because infix notation with <= is generally used when both arguments are known upfront, we optimize for readability with partial application.

lte(2, 1) // => true (1 is less than 2)
lte(2, 2) // => true (2 is equal to 2)
filter(lte(3), [1, 2, 3, 4, 5]) // => [1, 2, 3]

map

(a -> b) -> [a] -> [b]

Applies a transformation function to all elements in an array, returning a new array containing the results of those transformations.

map(x => x * 2, [1, 2, 3, 4, 5]) // => [2, 4, 6, 8, 10]

mapIndexed

((a, Integer) -> b) -> [a] -> [b]

Applies a transformation function to all elements in an array, returning a new array containing the results of those transformations. This is the same as map, but additionally provides the index of the each element as an argument to the transformation function.

const xform = (x, idx) => idx % 2 === 0 ? x * 2 : x
mapIndexed(xform, [1, 2, 3, 4, 5]) => [2, 2, 6, 4, 5]

mapKeys

(a -> b) -> {a:v} -> {b:v}

Iterates over all own, enumerable keys of an object, transforming each key with the provided function.

mapKeys(prepend('myKey_'), { a: 1, b: 2 }) // => { myKey_a: 1, myKey_b: 2 }

mapValues

(a -> b) -> {k:a} -> {k:b}

Iterates over all own, enumerable keys of an object, applying the transformation function to the value associated with each key. Returns a new object with the same keys mapped to the new values.

mapValues(multiply(2), { a: 1, b: 2, c: 3 }) // => { a: 2, b: 4, c: 6 }

max

[Number] -> Number

Returns the greatest number from a list of numbers.

max([1, 2, 3, 4, 5]) // => 5

mean

[Number] -> Number

Returns the mean (average) of all numbers in a list.

mean([1, 2, 3, 4, 5, 6]) // => 3.5

merge

{k:v} -> {k:v} -> {k:v}


min

[Number] -> Number

Returns the smallest number from a list of numbers.

min([1, 2, 3, 4, 5]) // => 1

multiply

Number -> Number -> Number

Returns the product of two numbers.

multiply(2, 3) // => 6
map(multiply(2), [1, 2, 3, 4]) // => [2, 4, 6, 8]

of

a -> [a]

Unary function that returns the argument wrapped in an array.

of(1)   // => [1]
of([1]) // => [[1]]

omit

String k, Any v => [k] -> {k:v} -> {k:v}

omit(['a', 'b'], { a: 1, b: 2, c: 3, d: 4 }) // => { c: 3, d: 4 }

over

Lens k -> (v -> *) -> {k:v} -> {k:v}

Transforms the value at the focal point of a lens on a given object.

const nameLens = lensProp('name')
const user = { name: 'Michael' }

over(lensProp('name'), toUpper, user) // => { name: 'MICHAEL' }
console.log(user)                     // => { name: 'Michael' }

pair

a -> b -> [a, b]

Binary function that returns the two arguments as a tuple.

pair(1, 2) // => [1, 2]

pick

String k ~> [k] -> {k:v} -> {k:v}

null

pipe

((a, b, ..., f -> g), (g -> h), ..., (y -> z)) -> ((a, b, ..., f) -> z

Takes a series of functions and wraps them in a single, curried function that, when called, invokes the original functions from left to right, passing the result of each function call as the argument to the next. The result of the rightmost function call is the final return value. This is the same concept as compose, but runs the functions from left -> right. Note that all functions except for the first (leftmost) must be unary (accept only a single argument), because functions can only return a single value.

const getFriends = pipe(prop('friends')
                        map(toUpper),
                        join(', '))

const user = { friends: [{ name: 'Jim' }, { name: 'Dwight'}] }
getFriends(user) // => 'JIM, DWIGHT'

prepend

a -> [a] -> a | String -> String -> String


prop

String k -> {k:v} -> v

Returns the value of a given property on an object.

prop('name', { name: 'Bob' }) // => Bob
prop('name', {})              // => undefined

propEq

String k -> v -> {k:v} -> Boolean

Gets the value of a given property off of an object and returns whether or not it equals the target value. A deep comparison is used to determine equality.

propEq('name', 'Michael', { name: 'Michael' }) // => true
propEq('data', { id: 1 }, { data: { id: 1 }})  // => true

range

Integer -> Integer -> [Integer]

Returns containing all integers between at an initial value (inclusive) and an end value (exclusive). If you wish to specify a custom step, use rangeBy.

range(1, 5)  // => [1, 2, 3, 4]
range(0, -5) // => [0, -1, -2, -3, -4]

rangeBy

Number -> Number -> Number -> [Number]

Returns containing all numbers between at an initial value (inclusive) and an end value (exclusive), where each subsequent value has been incremented by the provided step.

rangeBy(4, 0, 17) // => [0, 4, 8, 12, 16]

reduce

((b, a) -> b) -> b -> [a] -> b

Reduces a list of values into a single value. Provided with a reducing function and initial accumulator value, this is accomplished by iterating through all elements of the list (from left -> right) and calling the reducing function with the current acumulator value and the next value in the list. The result of each function call is used as the accumulator in the next call. When the end of the list is reached, the final accumulator value is returned. If you wish to reduce the list from right -> left, use reduceRight.

const sum = reduce((acc, n) => acc + n, 0)
sum([1, 2, 3, 4, 5]) // => 15

reduceRight

((b, a) -> b) -> b -> [a]

The same as reduce, but runs the reducing function from right -> left.

Reduces a list of values into a single value. Provided with a reducing function and initial accumulator value, this is accomplished by iterating through all elements of the list (from right -> left) and calling the reducing function with the current acumulator value and the next value in the list. The result of each function call is used as the accumulator in the next call. When the head of the list is reached, the final accumulator value is returned. If you wish to reduce the list from left -> right, use reduce.

const reverse = reduce((acc, x) => [x].concat(acc), [])
reverse([1, 2, 3, 4]) // => [4, 3, 2, 1]

reject

(a -> Boolean) -> [a] -> [a]

Returns a subset of an array that excludes all items for which the predicate function returns true. This is the inverse of filter and is equivalent to filter(complement(predicate)).

reject(isEven, [1, 2, 3, 4, 5]) // => [1, 3, 5]

reverse

[a] -> [a]

Returns an array with all of the elements reversed.

reverse([1, 2, 3, 4]) // => [4, 3, 2, 1]

scan

(b, a -> b) -> b -> [a] -> [b]

Similar to reduce, but returns a list containing the accumulator value from each step in the reducing function.

// initial accumulator  --> 0
// first step:  0 + 1   --> 1
// second step: 1 + 2   --> 3
// third step:  3 + 3   --> 6
// fourth step: 6 + 4   --> 10
scan(add, 0, [1, 2, 3, 4]) // => [0, 1, 3, 6, 10]

set

Lens k -> v -> {k:v} -> {k:v}

Applies a value to the target of a lens and returns the result of the lens' setter.

const nameLens = lensProp('name')
const userA = { name: 'Joe' }
const userB = set(nameLens, 'Billy', userA)

console.log(userA) // => { name: 'Joe' }
console.log(userB) // => { name: 'Billy' }

split

String -> String -> [String]

Splits a string on some delimeter and returns an array containing the fragments of that string between the delimeter.

split(',', 'Jim, Bill, Bob') // => ['Jim', 'Bill', 'Bob']

subtract

Number -> Number -> Number

Returns the difference of two numbers. Because infix notation with - is generally used when both arguments are known upfront, we optimize for readability with partial application.

subtract(2, 5) // => 3 (5 - 2)
const subtract5 = subtract(5)
subtract5(10) // => 5
subtract5(15) // => 10

sum

[Number] -> Number

Returns the sum of all elements in an array.

sum([1, 10, 100]) // => 111
sum([])           // => 0

tail

[a] -> [a]

Returns a subset of a list containing all elements except the first. If the list is empty or has only one element, an empty list is returned.

tail([1, 2, 3, 4, 5]) // => [2, 3, 4, 5]
tail([1])             // => []
tail([])              // => []

take

Integer -> [a] -> [a]

Returns an array containing the first N elements of the target array. If N is greater than the length of the array, all elements are returned.

take(3, [1, 2, 3, 4, 5]) // => [1, 2, 3]
take(5, [1, 2, 3])       // => [1, 2, 3]
take(Infinity, [])       // => []

takeWhile

(a -> Boolean) -> [a] -> [a]

Returns a list containing all values from the original list up until the point at which the predicate returned false. This is done by iterating through the original list and testing each value in turn against the predicate function; as soon as the predicate function returns false, all future values are discarded, and only the values before the one that failed are selected. If the predicate function holds true for all values in the list, a copy of the entire list is returned.

takeUntil(isEven, [1, 3, 5, 4, 7, 9]) // => [1, 3, 5]
takeUntil(isEven, [1, 3, 5, 7, 9])    // => [1, 3, 5, 7, 9]

tap

(a -> *) -> a -> a

Wraps a unary function so that it is called with the argument supplied to it but its return value is ignored and the initial argument is returned instead. This is useful when you want to perform a side effect without interfering with an argument or composition.

const log = tap(x => console.log(x))

// logs: 1, 2, 2, 4, 3, 6, 4, 8
map(pipe(log, double, log), [1, 2, 3, 4]) // => [2, 4, 6, 8]

// Also useful when you want to step through a series of transformations
const trace = message => tap(x => console.log(message, x))

fetchUser()                    // => Promise
 .then(trace('Got user'))      // => User, logs "Got user [data]"
 .then(getContacts)            // => Promise
 .then(trace('Got contacts'))  // => Array<User>, logs "Got contacts [data]"
 .then(map(prop('name')))      // => Array<String>
 .then(trace('Contact names')) // => Array<String>, logs "Contact names [data]"

test

RegExp -> String -> Boolean

Returns whether or not a string is matched by a regular expression.

test(/bar/, 'foobarbaz') // => true
filter(test(/joe/i), ['Joe', 'Bill', 'joey'])) // => ['Joe', 'joey']

times

(Number -> a) -> Number -> [a]

Calls a function N times with the index of the call. Returns an array containing the result of each function call.

times(identity, 5) // => [0, 1, 2, 3, 4]

toLower

String -> String

Lower-cases all characters in a string.

toLower('Hi There')  // => 'hi there'
toLower('GoodBye')   // => 'goodbye'

toPairs

String k, Any v => {k:v} -> [[k, v]]

Converts all own enumerable keys in an object into a list of [key, value] pairs. If you have a list of these pairs and wish to conver them back into an object, use fromPairs.

toPairs({ a: 'foo', b: 'bar' }) // => [['a', 'foo'], ['b', 'bar']]

toUpper

String -> String

Upper-cases all characters in a string.

toUpper('hi there')  // => 'HI THERE'
toUpper('GoodBye')   // => 'GOODBYE'

trim

String -> String

Returns the string with all leading and trailing whitespace removed.

trim('  hello  ') // => 'hello'

type

a -> String

Returns the string representation of an argument. Note that this function provides certain conveniences: null and undefined are both treated as Nil, and promises return Promise rather than Object.

type(1)                 // => 'Number'
type('hello')           // => 'String'
type(true)              // => 'Boolean'
type({})                // => 'Object'
type([])                // => 'Array'
type(Promise.resolve()) // => 'Promise'
type(undefined)         // => 'Nil'
type(null)              // => 'Nil'

unless

(a -> Boolean) -> (a -> b) -> a -> a | b

Creates a unary function that dispatches to the provided function if the predicate returns false for the provided value. If the predicate returns true the argument is passed through unmodified. This is the complement of when.

const doubleIfNotEven = unless(isEven, multiply(2))
doubleIfNotEven(3) // => 6
doubleIfNotEven(2) // => 2

values

String k, Any v => {k:v} -> [v]

Returns an array containing the values of an object's own enumerable properties. Note that this ignores all inherited properties, and does not guarantee order due to discrepencies between JavaScript engines.

values({ a: 1, b: 2, c: 3 }) // => [1, 2, 3]
values({})                   // => []

// Inherited properties are ignored
class A {
  foo() {}
}
const a = new A()
a.bar = 'BAR'
values(a) // => ['BAR'] (foo is inherited from A's protoype and is ignored)

view

Lens k -> {k:v} -> v

Returns the value at the focal point of a lens on a given object.

const nameLens = lensProp('name')
view(nameLens, { name: 'Dwight' })  // => 'Dwight'
view(nameLens, { name: 'Michael' }) // => 'Michael'

when

(a -> Boolean) -> (a -> b) -> a -> a | b

Creates a unary function that, when invoked, checks its argument against the predicate function. If the predicate returns true, the handler function is called and its result returned. If the predicate returns false, the original argument is returned unmodified. You can think of when as shorthand for ifElse(predicate, xform, identity), though keep in mind that it only supports unary functions.

const doubleIfEven = when(isEven, multiply(2))

doubleIfEven(4) // => 8
doubleIfEven(5) // => 5
map(doubleIfEven, [1, 2, 3, 4, 5]) // => [1, 4, 3, 8, 5]

where

String k, (Any -> Boolean) Spec => {k:Spec} -> Boolean

const pred = where({ name: equals('Michael') })
pred({ name: 'Michael' }) // => true
pred({ name: 'Dwight' })  // => false

const people = [{ age: 12 }, { age: 14 }, { age: 18 }, { age: 22 }]
filter(where({ age: gte(18) }), people) // => [{ age: 18 }, { age: 22 }]

without

[a] -> [a] -> [a]

Excludes all elements of the first array from the second array.

without([1, 2], [1, 2, 3, 4, 2, 1, 7]) => [3, 4, 7]

zip

[a] -> [b] -> [[a, b]]

Returns an array of tuples generated by pairing elements of the first array with elements of the second array, by position. The result is truncated to the length of the shorter of the two input arrays.

zip(['a', 'b', 'c'], [1, 2, 3]) // => [['a', 1], ['b', 2], ['c', 3]]
zip(['a', 'b', 'c'], [1])       // => [['a', 1]]

zipObj

String k, Any v => [k] -> [v] -> {k:v}

Returns an object with keys/values generated by pairing elements of the first array (of keys) with elements of the second array (of values) by their position. The result is truncated to the length of the shorter of the two input arrays. If you wish to zip an array of [key, value] pairs, use fromPairs.

zipObj(['a', 'b', 'c'], [1, 2, 3]) // => { a: 1, b: 2, c: 3 }
zipObj(['a', 'b', 'c'], [1])       // => { a: 1 }

--

--

results matching ""

    No results matching ""