Merge two or more arrays. This method does not change the existing arrays,
but instead returns a new array, even if the other array is empty.
Data First
concat(data, other);
Parameters
data
The first items, these would be at the beginning of the new
array.
other
The remaining items, these would be at the end of the new
array.
Returns
Object
concat([1, 2, 3], ["a"]); // [1, 2, 3, 'a']
Data Last
concat(arr2)(arr1);
Parameters
other
The remaining items, these would be at the end of the new
array.
Returns
Object
concat(["a"])([1, 2, 3]); // [1, 2, 3, 'a']
countBy
Array
Categorize and count elements in an array using a defined callback function.
The callback function is applied to each element in the array to determine
its category and then counts how many elements fall into each category.
Excludes the values from other array. The output maintains the same order
as the input. The inputs are treated as multi-sets/bags (multiple copies of
items are treated as unique items).
Drop the first n items from data based on the provided ordering criteria. This allows you to avoid sorting the array before dropping the items. The complexity of this function is O(Nlogn) where N is the length of the array.
For the opposite operation (to keep n elements) see takeFirstBy.
Data First
dropFirstBy(data, n, ...rules);
Parameters
data
The input array.
n
The number of items to drop. If `n` is non-positive no items would be dropped and a *clone* of the input would be returned, if `n` is bigger then data.length no items would be returned.
rules
A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.
The number of items to drop. If `n` is non-positive no items would be dropped and a *clone* of the input would be returned, if `n` is bigger then data.length no items would be returned.
rules
A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.
Removes elements from the end of the array until the predicate returns false.
The predicate is applied to each element in the array starting from the end and moving towards the beginning, until the predicate returns false. The returned array includes elements from the beginning of the array, up to and including the element that produced false for the predicate.
Removes elements from the beginning of the array until the predicate returns false.
The predicate is applied to each element in the array, until the predicate returns false. The returned array includes the rest of the elements, starting with the element that produced false for the predicate.
Creates a shallow copy of a portion of a given array, filtered down to just
the elements from the given array that pass the test implemented by the
provided function. Equivalent to Array.prototype.filter.
Data First
filter(data, predicate);
Parameters
data
The array to filter.
predicate
A function to execute for each element in the array. It
should return `true` to keep the element in the resulting array, and `false`
otherwise. A type-predicate can also be used to narrow the result.
Returns the first element in the provided array that satisfies the provided
testing function. If no values satisfy the testing function, undefined is
returned.
Similar functions:
findLast - If you need the last element that satisfies the provided testing function.
findIndex - If you need the index of the found element in the array.
indexOf - If you need to find the index of a value.
includes - If you need to find if a value exists in an array.
some - If you need to find if any element satisfies the provided testing function.
filter - If you need to find all elements that satisfy the provided testing function.
Data First
find(data, predicate);
Parameters
data
The items to search in.
predicate
A function to execute for each element in the array. It
should return `true` to indicate a matching element has been found, and
`false` otherwise. A type-predicate can also be used to narrow the result.
Returns
Object
find([1, 3, 4, 6], (n) => n % 2 === 0); // => 4
Data Last
find(predicate)(data);
Parameters
predicate
A function to execute for each element in the array. It
should return `true` to indicate a matching element has been found, and
`false` otherwise. A type-predicate can also be used to narrow the result.
Returns the index of the first element in an array that satisfies the
provided testing function. If no elements satisfy the testing function, -1 is
returned.
See also the find method, which returns the first element that satisfies
the testing function (rather than its index).
Data First
findIndex(data, predicate);
Parameters
data
The items to search in.
predicate
A function to execute for each element in the array. It
should return a `true` to indicate a matching element has been found, and a
`false` otherwise.
Iterates the array in reverse order and returns the value of the first
element that satisfies the provided testing function. If no elements satisfy
the testing function, undefined is returned.
Similar functions:
find - If you need the first element that satisfies the provided testing function.
findLastIndex - If you need the index of the found element in the array.
lastIndexOf - If you need to find the index of a value.
includes - If you need to find if a value exists in an array.
some - If you need to find if any element satisfies the provided testing function.
filter - If you need to find all elements that satisfy the provided testing function.
Data First
findLast(data, predicate);
Parameters
data
The items to search in.
predicate
A function to execute for each element in the array. It
should return `true` to indicate a matching element has been found, and
`false` otherwise. A type-predicate can also be used to narrow the result.
A function to execute for each element in the array. It
should return `true` to indicate a matching element has been found, and
`false` otherwise. A type-predicate can also be used to narrow the result.
Iterates the array in reverse order and returns the index of the first
element that satisfies the provided testing function. If no elements satisfy
the testing function, -1 is returned.
See also findLast which returns the value of last element that satisfies
the testing function (rather than its index).
Data First
findLastIndex(data, predicate);
Parameters
data
The items to search in.
predicate
A function to execute for each element in the array. It
should return `true` to indicate a matching element has been found, and
`false` otherwise.
pipe( [1, 2, 4, 8, 16], filter((x) => x > 3), first(), (x) => x + 1,); // => 5
firstBy
Array
Find the first element in the array that adheres to the order rules provided. This is a superset of what a typical maxBy or minBy function would do as it allows defining "tie-breaker" rules when values are equal, and allows comparing items using any logic. This function is equivalent to calling first(sortBy(...)) but runs at O(n) instead of O(nlogn).
Use nthBy if you need an element other that the first, or takeFirstBy if you more than just the first element.
Data First
firstBy(data, ...rules);
Parameters
data
An array of items.
rules
A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.
A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.
Creates a new array with all sub-array elements concatenated into it
recursively up to the specified depth. Equivalent to the built-in
Array.prototype.flat method.
Data First
flat(data);
Parameters
data
The items to flatten.
depth
The depth level specifying how deep a nested array structure
should be flattened. Defaults to 1. Non literal values (those typed as
`number`cannot be used. `Infinity`, `Number.POSITIVE_INFINITY` and
`Number.MAX_VALUE` are all typed as `number` and can't be used either. For
"unlimited" depth use a literal value that would exceed your expected
practical maximum nesting level.
Returns a new array formed by applying a given callback function to each
element of the array, and then flattening the result by one level. It is
identical to a map followed by a flat of depth 1
(flat(map(data, ...args))), but slightly more efficient than calling those
two methods separately. Equivalent to Array.prototype.flatMap.
Data First
flatMap(data, callbackfn);
Parameters
data
The items to map and flatten.
callbackfn
A function to execute for each element in the array. It
should return an array containing new elements of the new array, or a single
non-array value to be added to the new array.
A function to execute for each element in the array. It
should return an array containing new elements of the new array, or a single
non-array value to be added to the new array.
Executes a provided function once for each array element. Equivalent to
Array.prototype.forEach.
The dataLast version returns the original array (instead of not returning
anything (void)) to allow using it in a pipe. When not used in a pipe the
returned array is equal to the input array (by reference), and not a shallow
copy of it!
Data First
forEach(data, callbackfn);
Parameters
data
The values that would be iterated on.
callbackfn
A function to execute for each element in the array.
Returns
void
forEach([1, 2, 3], (x) => { console.log(x);});
Data Last
forEach(callbackfn)(data);
Parameters
callbackfn
A function to execute for each element in the array.
Groups the elements of a given iterable according to the string values
returned by a provided callback function. The returned object has separate
properties for each group, containing arrays with the elements in the group.
Unlike the built in Object.groupBy this function also allows the callback to
return undefined in order to exclude the item from being added to any
group.
If you are grouping objects by a property of theirs (e.g.
groupBy(data, ({ myProp }) => myProp) or groupBy(data, prop('myProp')))
consider using groupByProp (e.g. groupByProp(data, 'myProp')) instead,
as it would provide better typing.
Data First
groupBy(data, callbackfn);
Parameters
data
The items to group.
callbackfn
A function to execute for each element in the iterable.
It should return a value indicating the group of the current element, or
`undefined` when the item should be excluded from any group.
A function to execute for each element in the iterable.
It should return a value indicating the group of the current element, or
`undefined` when the item should be excluded from any group.
Groups the elements of an array of objects based on the values of a
specified property of those objects. The result would contain a property for
each unique value of the specific property, with it's value being the input
array filtered to only items that have that property set to that value.
For any object where the property is missing, or if it's value is
undefined the item would be filtered out.
The grouping property is enforced at the type level to exist in at least one
item and to never have a value that cannot be used as an object key (e.g. it
must be PropertyKey | undefined).
The resulting arrays are filtered with the prop and it's value as a
type-guard, effectively narrowing the items in each output arrays. This
means that when the grouping property is the discriminator of a
discriminated union type each output array would contain just the subtype for
that value.
If you need more control over the grouping you should use groupBy instead.
Checks if the given array has at least the defined number of elements. When
the minimum used is a literal (e.g. 3) the output is refined accordingly so
that those indices are defined when accessing the array even when using
typescript's 'noUncheckedIndexAccess'.
Data First
hasAtLeast(data, minimum);
Parameters
data
The input array.
minimum
The minimum number of elements the array must have.
Returns a list of elements that exist in both array. The output maintains the
same order as the input. The inputs are treated as multi-sets/bags (multiple
copies of items are treated as unique items).
Joins the elements of the array by: casting them to a string and
concatenating them one to the other, with the provided glue string in between
every two elements.
When called on a tuple and with stricter item types (union of literal values,
the result is strictly typed to the tuples shape and it's item types).
pipe( [1, 2, 4, 8, 16], filter((x) => x > 3), last(), (x) => x + 1,); // => 17
length
Array
Counts values of the collection or iterable.
Data First
length(array);
Parameters
items
The input data.
Returns
number
length([1, 2, 3]); // => 3
Data Last
length()(array);
Parameters
Returns
Object
pipe([1, 2, 3], length()); // => 3
map
LazyArray
Creates a new array populated with the results of calling a provided function
on every element in the calling array. Equivalent to Array.prototype.map.
Data First
map(data, callbackfn);
Parameters
data
The array to map.
callbackfn
A function to execute for each element in the array. Its
return value is added as a single element in the new array.
Map each element of an array into an object using a defined mapper that
converts each item into an object entry (a tuple of [<key>, <value>]).
There are several other functions that could be used to build an object from
an array:
fromKeys - Builds an object from an array of keys and a mapper for
values.
indexBy - Builds an object from an array of values and a mapper for
keys.
pullObject - Builds an object from an array of items with a mapper for
values and another mapper for keys.
fromEntries - Builds an object from an array of key-value pairs.
Warning: We strongly advise against using this function unless it is
used with a huge input array and your app has stringent memory/gc
constraints. We recommend that in most cases you should use pullObject,
or the composition fromEntries(map(array, fn)). This function will be
deprecated and removed in future versions of the library!
Data First
mapToObj(array, fn);
Parameters
array
The array to map.
fn
The mapping function, which should return a tuple of [key, value], similar to Object.fromEntries.
Applies a function on each element of the array, using the result of the
previous application, and returns an array of the successively computed
values.
Data First
mapWithFeedback(data, callbackfn, initialValue);
Parameters
data
The array to map over.
callbackfn
The callback function that receives the previous value,
the current element.
Retrieves the element that would be at the given index if the array were sorted according to specified rules. This function uses the QuickSelect algorithm running at an average complexity of O(n). Semantically it is equivalent to sortBy(data, ...rules).at(index) which would run at O(nlogn).
See also firstBy which provides an even more efficient algorithm and a stricter return type, but only for index === 0. See takeFirstBy to get all the elements up to and including index.
Data First
nthBy(data, index, ...rules);
Parameters
data
The input array.
index
The zero-based index for selecting the element in the sorted order. Negative indices count backwards from the end.
rules
A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.
Returns
Object
nthBy([2, 1, 4, 5, 3], 2, identity()); // => 3
Data Last
nthBy(index, ...rules)(data);
Parameters
index
The zero-based index for selecting the element in the sorted order. Negative indices count backwards from the end.
rules
A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.
Splits a collection into two groups, the first of which contains elements the
predicate type guard passes, and the second one containing the rest.
Data First
partition(data, predicate);
Parameters
data
The items to split.
predicate
A function to execute for each element in the array. It
should return `true` to add the element to the first partition, and and
`false` to add the element to the other partition. A type-predicate can also
be used to narrow the result.
A function to execute for each element in the array. It
should return `true` to add the element to the first partition, and and
`false` to add the element to the other partition. A type-predicate can also
be used to narrow the result.
Calculates the rank of an item in an array based on rules. The rank is the position where the item would appear in the sorted array. This function provides an efficient way to determine the rank in O(n) time, compared to O(nlogn) for the equivalent sortedIndex(sortBy(data, ...rules), item).
Data First
rankBy(data, item, ...rules);
Parameters
data
The input array.
item
The item whose rank is to be determined.
rules
A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.
A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.
Executes a user-supplied "reducer" callback function on each element of the
array, in order, passing in the return value from the calculation on the
preceding element. The final result of running the reducer across all
elements of the array is a single value. Equivalent to
Array.prototype.reduce.
Data First
reduce(data, callbackfn, initialValue);
Parameters
data
The items to reduce.
callbackfn
A function to execute for each element in the array. Its
return value becomes the value of the accumulator parameter on the next
invocation of callbackFn. For the last invocation, the return value becomes
the return value of reduce().
initialValue
A value to which accumulator is initialized the first
time the callback is called. CallbackFn starts executing with the first value
in the array as currentValue.
A function to execute for each element in the array. Its
return value becomes the value of the accumulator parameter on the next
invocation of callbackFn. For the last invocation, the return value becomes
the return value of reduce().
initialValue
A value to which accumulator is initialized the first
time the callback is called. CallbackFn starts executing with the first value
in the array as currentValue.
Returns a random subset of size sampleSize from array.
Maintains and infers most of the typing information that could be passed
along to the output. This means that when using tuples, the output will be
a tuple too, and when using literals, those literals would be preserved.
The items in the result are kept in the same order as they are in the input.
If you need to get a shuffled response you can pipe the shuffle function
after this one.
Shuffles the input array, returning a new array with the same elements in a random order.
Data First
shuffle(array);
Parameters
items
The array to shuffle.
Returns
Object
shuffle([4, 2, 7, 5]); // => [7, 5, 4, 2]
Data Last
shuffle()(array);
Parameters
Returns
Object
pipe([4, 2, 7, 5], shuffle()); // => [7, 5, 4, 2]
sort
Array
Sorts an array. The comparator function should accept two values at a time
and return a negative number if the first value is smaller, a positive number
if it's larger, and zero if they are equal. Sorting is based on a native
sort function.
Data First
sort(items, cmp);
Parameters
items
The array to sort.
cmp
The comparator function.
Returns
Object
sort([4, 2, 7, 5], (a, b) => a - b); // => [2, 4, 5, 7]
Data Last
sort(cmp)(items);
Parameters
cmp
The comparator function.
Returns
Object
pipe( [4, 2, 7, 5], sort((a, b) => a - b),); // => [2, 4, 5, 7]
sortBy
Array
Sorts data using the provided ordering rules. The sort is done via the
native Array.prototype.sort but is performed on a shallow copy of the array
to avoid mutating the original data.
There are several other functions that take order rules and bypass the
need to sort the array first (in O(nlogn) time):
rankBy === sortedIndex(sortBy(data, ...rules), item), O(n).
Refer to the docs for more details.
Data First
sortBy(data, ...rules);
Parameters
array
The input array.
sortRules
A variadic array of order rules defining the sorting
criteria. Each order rule is a projection function that extracts a comparable
value from the data. Sorting is based on these extracted values using the
native `<` and `>` operators. Earlier rules take precedence over later ones.
Use the syntax `[projection, "desc"]` for descending order.
A variadic array of order rules defining the sorting
criteria. Each order rule is a projection function that extracts a comparable
value from the data. Sorting is based on these extracted values using the
native `<` and `>` operators. Earlier rules take precedence over later ones.
Use the syntax `[projection, "desc"]` for descending order.
Find the insertion position (index) of an item in an array with items sorted
in ascending order; so that splice(sortedIndex, 0, item) would result in
maintaining the array's sort-ness. The array can contain duplicates.
If the item already exists in the array the index would be of the first
occurrence of the item.
Find the insertion position (index) of an item in an array with items sorted
in ascending order using a value function; so that
splice(sortedIndex, 0, item) would result in maintaining the arrays sort-
ness. The array can contain duplicates.
If the item already exists in the array the index would be of the first
occurrence of the item.
Runs in O(logN) time.
See also:
findIndex - scans a possibly unsorted array in-order (linear search).
sortedIndex - like this function, but doesn't take a callbackfn.
sortedLastIndexBy - like this function, but finds the last suitable index.
rankBy - scans a possibly unsorted array in-order, returning the index based on a sorting criteria.
Data First
sortedIndexBy(data, item, valueFunction);
Parameters
data
The (ascending) sorted array.
item
The item to insert.
valueFunction
All comparisons would be performed on the result of
calling this function on each compared item. Preferably this function should
return a `number` or `string`. This function should be the same as the one
provided to sortBy to sort the array. The function is called exactly once on
each items that is compared against in the array, and once at the beginning
on `item`. When called on `item` the `index` argument is `undefined`.
Performs a binary search for the index of the item at which the predicate
stops returning true. This function assumes that the array is "sorted" in
regards to the predicate, meaning that running the predicate as a mapper on
it would result in an array [...true[], ...false[]].
This stricter requirement from the predicate provides us 2 benefits over
findIndex which does a similar thing:
It would run at O(logN) time instead of O(N) time.
It always returns a value (it would return data.length if the
predicate returns true for all items).
This function is the basis for all other sortedIndex functions which search
for a specific item in a sorted array, and it could be used to perform
similar efficient searches.
sortedIndex - scans a sorted array with a binary search, find the first suitable index.
Find the insertion position (index) of an item in an array with items sorted
in ascending order; so that splice(sortedIndex, 0, item) would result in
maintaining the array's sort-ness. The array can contain duplicates.
If the item already exists in the array the index would be of the last
occurrence of the item.
Find the insertion position (index) of an item in an array with items sorted
in ascending order using a value function; so that
splice(sortedIndex, 0, item) would result in maintaining the arrays sort-
ness. The array can contain duplicates.
If the item already exists in the array the index would be of the last
occurrence of the item.
Runs in O(logN) time.
See also:
findIndex - scans a possibly unsorted array in-order (linear search).
sortedLastIndex - a simplified version of this function, without a callbackfn.
sortedIndexBy - like this function, but returns the first suitable index.
rankBy - scans a possibly unsorted array in-order, returning the index based on a sorting criteria.
Data First
sortedLastIndexBy(data, item, valueFunction);
Parameters
data
The (ascending) sorted array.
item
The item to insert.
valueFunction
All comparisons would be performed on the result of
calling this function on each compared item. Preferably this function should
return a `number` or `string`. This function should be the same as the one
provided to sortBy to sort the array. The function is called exactly once on
each items that is compared against in the array, and once at the beginning
on `item`. When called on `item` the `index` argument is `undefined`.
All comparisons would be performed on the result of
calling this function on each compared item. Preferably this function should
return a `number` or `string`. This function should be the same as the one
provided to sortBy to sort the array. The function is called exactly once on
each items that is compared against in the array, and once at the beginning
on `item`. When called on `item` the `index` argument is `undefined`.
Returns the sum of the elements of an array using the provided mapper.
Works for both number and bigint mappers, but not mappers that return both
types.
IMPORTANT: The result for empty arrays would be 0 (number) regardless of
the type of the mapper; to avoid adding this to the return type for cases
where the array is known to be non-empty you can use hasAtLeast or
isEmpty to guard against this case.
Swaps the positions of two elements in an array or string at the provided indices.
Negative indices are supported and would be treated as an offset from the end of the array. The resulting type thought would be less strict than when using positive indices.
If either index is out of bounds the result would be a shallow copy of the input, as-is.
Data First
swapIndices(data, index1, index2);
Parameters
data
The item to be manipulated. This can be an array, or a string.
Take the first n items from data based on the provided ordering criteria. This allows you to avoid sorting the array before taking the items. The complexity of this function is O(Nlogn) where N is the length of the array.
For the opposite operation (to drop n elements) see dropFirstBy.
Data First
takeFirstBy(data, n, ...rules);
Parameters
data
The input array.
n
The number of items to take. If `n` is non-positive no items would be returned, if `n` is bigger then data.length a *clone* of `data` would be returned.
rules
A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.
The number of items to take. If `n` is non-positive no items would be returned, if `n` is bigger then data.length a *clone* of `data` would be returned.
rules
A variadic array of order rules defining the sorting criteria. Each order rule is a projection function that extracts a comparable value from the data. Sorting is based on these extracted values using the native `<` and `>` operators. Earlier rules take precedence over later ones. Use the syntax `[projection, "desc"]` for descending order.
Returns elements from the end of the array until the predicate returns false.
The returned elements will be in the same order as in the original array.
Returns a new array containing only one copy of each element in the original
list transformed by a function. Elements are compared by reference using Set.
Data First
uniqueBy(data, keyFunction);
Parameters
data
The array to filter.
keyFunction
Extracts a value that would be used to compare elements.
Creates a new list from two supplied lists by pairing up equally-positioned
items. The length of the returned list will match the shortest of the two
inputs.
The function applied to each position of the list.
Returns
Array
zipWith(["1", "2", "3"], ["a", "b", "c"], (a, b) => a + b); // => ['1a', '2b', '3c']
Data Last
zipWith(second, fn)(first);
Parameters
second
The second input list.
fn
The function applied to each position of the list.
Returns
Object
pipe( ["1", "2", "3"], zipWith(["a", "b", "c"], (a, b) => a + b),); // => ['1a', '2b', '3c']
function
conditional
Function
Executes a transformer function based on the first matching predicate,
functioning like a series of if...else if... statements. It sequentially
evaluates each case and, upon finding a truthy predicate, runs the
corresponding transformer, and returns, ignoring any further cases, even if
they would match.
NOTE: Some type-predicates may fail to narrow the param type of their
transformer; in such cases wrap your type-predicate in an anonymous arrow
function: e.g., instead of
conditional(..., [myTypePredicate, myTransformer], ...), use
conditional(..., [($) => myTypePredicate($), myTransformer], ...).
To add a a default, catch-all, case you can provide a single callback
function (instead of a 2-tuple) as the last case. This is equivalent to
adding a case with a trivial always-true predicate as it's condition (see
example).
For simpler cases you should also consider using when instead.
Due to TypeScript's inability to infer the result of negating a type-
predicate we can't refine the types used in subsequent cases based on
previous conditions. Using a switch (true) statement or ternary operators
is recommended for more precise type control when such type narrowing is
needed.
!IMPORTANT! - Unlike similar implementations in Lodash and Ramda, the Remeda
implementation doesn't implicitly return undefined as a fallback when
when none of the cases match; and instead throws an exception in those
cases! You have to explicitly provide a default case, and can use
constant(undefined) as your last case to replicate that behavior.
Data First
conditional(data, ...cases);
Parameters
data
The input data to be evaluated against the provided cases.
A function that takes any arguments and returns the provided value on every
invocation. This is useful to provide trivial implementations for APIs or in
combination with a ternary or other conditional execution to allow to short-
circuit more complex implementations for a specific case.
Notice that this is a dataLast impl where the function needs to be invoked
to get the "do nothing" function.
See also:
doNothing - A function that doesn't return anything.
identity - A function that returns the first argument it receives.
Data Last
constant(value);
Parameters
value
The constant value that would be returned on every invocation.
The value is not copied/cloned on every invocation so care should be taken
with mutable objects (like arrays, objects, Maps, etc...).
Wraps func with a debouncer object that "debounces" (delays) invocations of the function during a defined cool-down period (waitMs). It can be configured to invoke the function either at the start of the cool-down period, the end of it, or at both ends (timing).
It can also be configured to allow invocations during the cool-down period (maxWaitMs).
It stores the latest call's arguments so they could be used at the end of the cool-down period when invoking func (if configured to invoke the function at the end of the cool-down period).
It stores the value returned by func whenever its invoked. This value is returned on every call, and is accessible via the cachedValue property of the debouncer. Its important to note that the value might be different from the value that would be returned from running func with the current arguments as it is a cached value from a previous invocation.
Important: The cool-down period defines the minimum between two invocations, and not the maximum. The period will be extended each time a call is made until a full cool-down period has elapsed without any additional calls.
! DEPRECATED: This implementation of debounce is known to have issues and might not behave as expected. It should be replaced with the funnel utility instead. The test file funnel.remeda-debounce.test.ts offers a reference implementation that replicates debounce via funnel!
Data First
debounce(func, options);
Parameters
func
The function to debounce, the returned `call` function will have
the exact same signature.
options
An object allowing further customization of the debouncer:
- `timing?: 'leading' | 'trailing' |'both'`. The default is `'trailing'`.
`leading` would result in the function being invoked at the start of the
cool-down period; `trailing` would result in the function being invoked at
the end of the cool-down period (using the args from the last call to the
debouncer). When `both` is selected the `trailing` invocation would only
take place if there were more than one call to the debouncer during the
cool-down period. **DEFAULT: 'trailing'**
- `waitMs?: number`. The length of the cool-down period in milliseconds. The
debouncer would wait until this amount of time has passed without **any**
additional calls to the debouncer before triggering the end-of-cool-down-
period event. When this happens, the function would be invoked (if `timing`
isn't `'leading'`) and the debouncer state would be reset. **DEFAULT: 0**
- `maxWaitMs?: number`. The length of time since a debounced call (a call
that the debouncer prevented from being invoked) was made until it would be
invoked. Because the debouncer can be continually triggered and thus never
reach the end of the cool-down period, this allows the function to still
be invoked occasionally. IMPORTANT: This param is ignored when `timing` is
`'leading'`.
A function that takes any arguments and does nothing with them. This is
useful as a placeholder for any function or API that requires a void
function (a function that doesn't return a value). This could also be used in
combination with a ternary or other conditional execution to allow disabling
a function call for a specific case.
Notice that this is a dataLast impl where the function needs to be invoked
to get the "do nothing" function.
See also:
constant - A function that ignores it's arguments and returns the same value on every invocation.
identity - A function that returns the first argument it receives.
Creates a funnel that controls the timing and execution of callback. Its
main purpose is to manage multiple consecutive (usually fast-paced) calls,
reshaping them according to a defined batching strategy and timing policy.
This is useful when handling uncontrolled call rates, such as DOM events or
network traffic. It can implement strategies like debouncing, throttling,
batching, and more.
An optional reducer function can be provided to allow passing data to the
callback via calls to call (otherwise the signature of call takes no
arguments).
Typing is inferred from callbacks param, and from the rest params that
the optional reducer function accepts. Use explicit types for these
to ensure that everything else is well-typed.
Notice that this function constructs a funnel object, and does not
execute anything when called. The returned object should be used to execute
the funnel via the its call method.
Debouncing: use minQuietPeriodMs and any triggerAt.
Throttling: use minGapMs and triggerAt: "start" or "both".
The main function that would be invoked periodically based
on `options`. The function would take the latest result of the `reducer`; if
no calls where made since the last time it was invoked it will not be
invoked. (If a return value is needed, it should be passed via a reference or
via closure to the outer scope of the funnel).
options
An object that defines when `execute` should be invoked,
relative to the calls of `call`. An empty/missing options object is
equivalent to setting `minQuietPeriodMs` to `0`.
Creates a function that calls func with partial put after the arguments
it receives. Note that this doesn't support functions with both optional
and rest parameters.
Can be thought of as "freezing" some portion of a function's arguments,
resulting in a new function with a simplified signature.
Useful for converting a data-first function to a data-last one.
Performs left-to-right function composition, passing data through functions
in sequence. Each function receives the output of the previous function,
creating a readable top-to-bottom data flow that matches how the
transformation is executed. This enables converting deeply nested function
calls into clear, sequential steps without temporary variables.
When consecutive functions with a lazy tag (e.g., map, filter, take,
drop, forEach, etc...) are used together, they process data item-by-item
rather than creating intermediate arrays. This enables early termination
when only partial results are needed, improving performance for large
datasets and expensive operations.
Functions are only evaluated lazily when their data-last form is used
directly in the pipe. To disable lazy evaluation, use data-first calls via
arrow functions: ($) => map($, callback) instead of map(callback).
Any function can be used in pipes, not just Remeda utilities. For creating
custom functions with currying and lazy evaluation support, see the purry
utility.
A "headless" variant piped is available for creating reusable pipe
functions without initial data.
IMPORTANT: During lazy evaluation, callbacks using the third parameter (the
input array) receive only items processed up to that point, not the complete
array.
Data First
pipe(data, ...functions);
Parameters
data
The input data.
Returns
Object
pipe([1, 2, 3], map(multiply(3))); //=> [3, 6, 9]// = Early termination with lazy evaluation =pipe( hugeArray, map(expensiveComputation), filter(complexPredicate), // Only processes items until 2 results are found, then stops. // Most of hugeArray never gets processed. take(2),);// = Custom logic within a pipe =pipe( input, toLowerCase(), normalize, ($) => validate($, CONFIG), split(","), unique(),);// = Migrating nested transformations to pipes =// Nestedconst result = prop( mapValues(groupByProp(users, "department"), length()), "engineering",);// Pipedconst result = pipe( users, groupByProp("department"), mapValues(length()), prop("engineering"),);// = Using the 3rd param of a callback =// The following would print out `data` in its entirety for each value// of `data`.forEach([1, 2, 3, 4], (_item, _index, data) => { console.log(data);}); //=> "[1, 2, 3, 4]" logged 4 times// But with `pipe` data would only contain the items up to the current// indexpipe( [1, 2, 3, 4], forEach((_item, _index, data) => { console.log(data); }),); //=> "[1]", "[1, 2]", "[1, 2, 3]", "[1, 2, 3, 4]"
piped
Function
Data-last version of pipe. See pipe documentation for full details.
Use piped when you need to pass a transformation as a callback to
functions like map and filter, where the data type can be inferred
from the call site.
IMPORTANT: piped does not work as a "function factory" in order to create
standalone utility functions; because TypeScript cannot infer the input data
type (without requiring to explicitly define all type params for all
functions in the pipe). We recommend defining the function explicitly, and
then use pipe in its implementation.
Creates a function with dataFirst and dataLast signatures.
purry is a dynamic function and it's not type safe. It should be wrapped by
a function that have proper typings. Refer to the example below for correct
usage.
!IMPORTANT: functions that simply call purry and return the result (like
almost all functions in this library) should return unknown themselves if
an explicit return type is required. This is because we currently don't
provide a generic return type that is built from the input function, and
crafting one manually isn't worthwhile as we rely on function declaration
overloading to combine the types for dataFirst and dataLast invocations!
purry(fn, args);
Parameters
fn
The function to purry.
args
The arguments.
lazy
A lazy version of the function to purry.
Returns
unknown
function _findIndex(array, fn) { for (let i = 0; i < array.length; i++) { if (fn(array[i])) { return i; } } return -1;}// data-firstfunction findIndex<T>(array: T[], fn: (item: T) => boolean): number;// data-lastfunction findIndex<T>(fn: (item: T) => boolean): (array: T[]) => number;function findIndex(...args: unknown[]) { return purry(_findIndex, args);}
when
Function
Conditionally run a function based on a predicate, returning its result (similar to
the ?: (ternary) operator.)
If the optional onFalse function is not provided, the data will be passed
through in those cases.
Supports type predicates to refine the types for both branches and the return
value.
Additional arguments are passed to all functions. In data-first calls, they
are taken as variadic arguments; but in data-last calls, they are when the
curried function itself is called.
pipe({ a: 1 }, hasProp("a")); //=> truefilter([] as { a?: number }[], hasProp("a")); //=> typed as { a: number }[]
hasSubObject
Guard
Checks if subObject is a sub-object of object, which means for every
property and value in subObject, there's the same property in object
with an equal value. Equality is checked with isDeepEqual.
Performs a deep structural comparison between two values to determine if
they are equivalent. For primitive values this is equivalent to ===, for
arrays the check would be performed on every item recursively, in order, and
for objects all props will be compared recursively.
The built-in Date and RegExp are special-cased and will be compared by their
values. Objects with a null prototype are comparable to plain objects by
their enumerable properties.
!IMPORTANT: TypedArrays and symbol properties of objects are not supported
right now and might result in unexpected behavior. Please open an issue in
the Remeda github project if you need support for these types.
The result would be narrowed to the second value so that the function can be
used as a type guard.
See:
isStrictEqual if you don't need a deep comparison and just want to
check for simple (===, Object.is) equality.
isShallowEqual if you need to compare arrays and objects "by-value" but
don't want to recurse into their values.
A function that checks if the passed parameter is empty.
This function has limited utility at the type level because negating it
does not yield a useful type in most cases because of TypeScript
limitations. Additionally, utilities which accept a narrower input type
provide better type-safety on their inputs. In most cases, you should use
one of the following functions instead:
isEmptyish - supports a wider range of cases, accepts any input including nullish values, and does a better job at narrowing the result.
hasAtLeast - when the input is just an array/tuple.
isStrictEqual - when you just need to check for a specific literal value.
isNullish - when you just care about null and undefined.
isTruthy - when you need to also filter number and boolean.
A function that checks if the input is empty. Empty is defined as anything
exposing a numerical length, or size property that is equal to 0. This
definition covers strings, arrays, Maps, Sets, plain objects, and custom
classes. Additionally, null and undefined are also considered empty.
number, bigint, boolean, symbol, and function will always return
false. RegExp, Date, and weak collections will always return true.
Classes and Errors are treated as plain objects: if they expose any public
property they would be considered non-empty, unless they expose a numerical
length or size property, which defines their emptiness regardless of
other properties.
This function has limited utility at the type level because negating it
does not yield a useful type in most cases because of TypeScript
limitations. Additionally, utilities which accept a narrower input type
provide better type-safety on their inputs. In most cases, you should use
one of the following functions instead:
isEmpty - provides better type-safety on inputs by accepting a narrower set of cases.
hasAtLeast - when the input is just an array/tuple.
isStrictEqual - when you just need to check for a specific literal value.
isNullish - when you just care about null and undefined.
isTruthy - when you need to also filter number and boolean.
Checks if the item is included in the container. This is a wrapper around
Array.prototype.includes and Set.prototype.has and thus relies on the
same equality checks that those functions do (which is reference equality,
e.g. ===). In some cases the input's type is also narrowed to the
container's item types.
Notice that unlike most functions, this function takes a generic item as it's
data and an array as it's parameter.
Checks if the given parameter is of type "object" via typeof, excluding null.
It's important to note that in JavaScript, many entities are considered objects, like Arrays, Classes, RegExps, Maps, Sets, Dates, URLs, Promise, Errors, and more. Although technically an object too, null is not considered an object by this function, so that its easier to narrow nullables.
For a more specific check that is limited to plain objects (simple struct/shape/record-like objects), consider using isPlainObject instead. For a simpler check that only removes null from the type prefer isNonNull or isDefined.
Data First
isObjectType(data);
Parameters
data
The variable to be checked for being an object type.
Checks if data is a "plain" object. A plain object is defined as an object with string keys and values of any type, including primitives, other objects, functions, classes, etc (aka struct/shape/record/simple). Technically, a plain object is one whose prototype is either Object.prototype or null, ensuring it does not inherit properties or methods from other object types.
This function is narrower in scope than isObjectType, which accepts any entity considered an "object" by JavaScript's typeof.
Note that Maps, Arrays, and Sets are not considered plain objects and would return false.
Performs a shallow structural comparison between two values to determine if
they are equivalent. For primitive values this is equivalent to ===, for
arrays a strict equality check would be performed on every item, in
order, and for objects props will be matched and checked for strict
equality; Unlike isDeepEqual where the function also recurses into each
item and value.
!IMPORTANT: symbol properties of objects are not supported right now and
might result in unexpected behavior. Please open an issue in the Remeda
github project if you need support for these types.
!IMPORTANT: Promise, Date, and RegExp, are shallowly equal, even when they
are semantically different (e.g. resolved promises); but isDeepEqual does
compare the latter 2 semantically by-value.
The result would be narrowed to the second value so that the function can be
used as a type guard.
See:
isStrictEqual if you don't need a deep comparison and just want to check
for simple (===, Object.is) equality.
isDeepEqual for a recursively deep check of arrays and objects.
Determines whether two values are functionally identical in all contexts.
For primitive values (string, number), this is done by-value, and for objects
it is done by-reference (i.e., they point to the same object in memory).
Under the hood we use both the === operator
and Object.is. This means that isStrictEqual(NaN, NaN) === true
(whereas NaN !== NaN), and isStrictEqual(-0, 0) === true (whereas
Object.is(-0, 0) === false).
The result would be narrowed to the second value so that the function can be
used as a type guard.
See:
isDeepEqual for a semantic comparison that allows comparing arrays and
objects "by-value", and recurses for every item.
isShallowEqual if you need to compare arrays and objects "by-value" but
don't want to recurse into their values.
Rounds up a given number to a specific precision.
If you'd like to round up to an integer (i.e. use this function with constant precision === 0),
use Math.ceil instead, as it won't incur the additional library overhead.
Data First
ceil(value, precision);
Parameters
value
The number to round up.
precision
The precision to round up to. Must be an integer between -15 and 15.
Rounds down a given number to a specific precision.
If you'd like to round down to an integer (i.e. use this function with constant precision === 0),
use Math.floor instead, as it won't incur the additional library overhead.
Data First
floor(value, precision);
Parameters
value
The number to round down.
precision
The precision to round down to. Must be an integer between -15 and 15.
Only number arrays are supported, as bigint is unable to represent fractional values.
IMPORTANT: The result for empty arrays would be undefined, regardless of
the type of the array. This approach improves type-checking and ensures that
cases where NaN might occur are handled properly. To avoid adding this to
the return type for cases where the array is known to be non-empty you can use
hasAtLeast or isEmpty to guard against this case.
Only number arrays are supported, as bigint is unable to represent fractional values.
IMPORTANT: The result for empty arrays would be undefined, regardless of
the type of the array. This approach improves type-checking and ensures that
cases where NaN might occur are handled properly. To avoid adding this to
the return type for cases where the array is known to be non-empty you can use
hasAtLeast or isEmpty to guard against this case.
Compute the product of the numbers in the array, or return 1 for an empty
array.
Works for both number and bigint arrays, but not arrays that contain both
types.
IMPORTANT: The result for empty arrays would be 1 (number) regardless of
the type of the array; to avoid adding this to the return type for cases
where the array is known to be non-empty you can use hasAtLeast or
isEmpty to guard against this case.
Generate a random bigint between from and to (inclusive).
! Important: In most environments this function uses
crypto.getRandomValues()
under-the-hood which is cryptographically strong. When the WebCrypto API
isn't available (Node 18) we fallback to an implementation that uses
Math.random()
which is NOT cryptographically secure.
Data First
randomBigInt(from, to);
Parameters
from
The minimum value.
to
The maximum value.
Returns
bigint
randomBigInt(1n, 10n); // => 5n
randomInteger
Number
Generate a random integer between from and to (inclusive).
!Important: This function uses Math.random() under-the-hood, which has two major limitations:
It generates 2^52 possible values, so the bigger the range, the less
uniform the distribution of values would be, and at ranges larger than that
some values would never come up.
It is not cryptographically secure and should not be used for security
scenarios.
Rounds a given number to a specific precision.
If you'd like to round to an integer (i.e. use this function with constant precision === 0),
use Math.round instead, as it won't incur the additional library overhead.
Data First
round(value, precision);
Parameters
value
The number to round.
precision
The precision to round to. Must be an integer between -15 and 15.
Sums the numbers in the array, or return 0 for an empty array.
Works for both number and bigint arrays, but not arrays that contain both
types.
IMPORTANT: The result for empty arrays would be 0 (number) regardless of
the type of the array; to avoid adding this to the return type for cases
where the array is known to be non-empty you can use hasAtLeast or
isEmpty to guard against this case.
The function doesn't do any checks on the input object. If the property
already exists it will be overwritten, and the type of the new value is not
checked against the previous type.
Use set to override values explicitly with better protections.
Creates a deep copy of the value. Supported types: plain objects,
Array, number, string, boolean, Date, and RegExp. Functions are
assigned by reference rather than copied. Class instances or any other
built-in type that isn't mentioned above are not supported (but might
work).
Data First
clone(data);
Parameters
data
The object to clone.
Returns
Object
clone({ foo: "bar" }); // {foo: 'bar'}
Data Last
clone()(data);
Parameters
Returns
Object
pipe({ foo: "bar" }, clone()); // {foo: 'bar'}
entries
Object
Returns an array of key/values of the enumerable properties of an object.
Creates a new object by applying functions that is included in evolver object parameter
to the data object parameter according to their corresponding path.
Functions included in evolver object will not be invoked
if its corresponding key does not exist in the data object.
Also, values included in data object will be kept as is
if its corresponding key does not exist in the evolver object.
Data First
evolve(data, evolver);
Parameters
object
Object whose value is applied to the corresponding function
that is defined in `evolver` at the same path.
evolver
Object that include functions that is applied to
the corresponding value of `data` object at the same path.
Iterate an object using a defined callback function.
The dataLast version returns the original object (instead of not returning
anything (void)) to allow using it in a pipe. The returned object is the
same reference as the input object, and not a shallow copy of it!
Data First
forEachObj(object, fn);
Parameters
data
The object who'se entries would be iterated on.
callbackfn
A function to execute for each element in the array.
Creates a new object from an array of tuples by pairing up first and second elements as {[key]: value}.
If a tuple is not supplied for any element in the array, the element will be ignored
If duplicate keys exist, the tuple with the greatest index in the input array will be preferred.
The strict option supports more sophisticated use-cases like those that would
result when calling the strict toPairs function.
There are several other functions that could be used to build an object from
an array:
fromKeys - Builds an object from an array of keys and a mapper for values.
indexBy - Builds an object from an array of values and a mapper for keys.
pullObject - Builds an object from an array of items with mappers for both keys and values.
Refer to the docs for more details.
Creates an object that maps each key in data to the result of mapper for
that key. Duplicate keys are overwritten, guaranteeing that mapper is run
for each item in data.
There are several other functions that could be used to build an object from
an array:
indexBy - Builds an object from an array of values and a mapper for keys.
pullObject - Builds an object from an array of items with mappers for both keys and values.
fromEntries - Builds an object from an array of key-value pairs.
Refer to the docs for more details.
Data First
fromKeys(data, mapper);
Parameters
data
An array of keys of the output object. All items in the array
would be keys in the output array.
mapper
Takes a key and returns the value that would be associated
with that key.
Merges two objects into one by combining their properties, effectively
creating a new object that incorporates elements from both. The merge
operation prioritizes the second object's properties, allowing them to
overwrite those from the first object with the same names.
Equivalent to { ...data, ...source }.
Data First
merge(data, source);
Parameters
data
The destination object, serving as the basis for the merge.
Properties from this object are included in the new object, but will be
overwritten by properties from the source object with matching keys.
source
The source object, whose properties will be included in the
new object. If properties in this object share keys with properties in the
destination object, the values from the source object will be used in the
new object.
The source object, whose properties will be included in the
new object. If properties in this object share keys with properties in the
destination object, the values from the source object will be used in the
new object.
Merges the source object into the destination object. The merge is similar to performing { ...destination, ... source } (where disjoint values from each object would be copied as-is, and for any overlapping props the value from source would be used); But for each prop (p), if bothdestination and source have a plain-object as a value, the value would be taken as the result of recursively deepMerging them (result.p === deepMerge(destination.p, source.p)).
Data First
mergeDeep(destination, source);
Parameters
destination
The object to merge into. In general, this object would have it's values overridden.
source
The object to merge from. In general, shared keys would be taken from this object.
Creates a shallow copy of the data, and then removes any keys that the
predicate rejects. Symbol keys are not passed to the predicate and would be
passed through to the output as-is.
See pickBy for a complementary function which starts with an empty object
and adds the entries that the predicate accepts. Because it is additive,
symbol keys will not be passed through to the output object.
Data First
omitBy(data, predicate);
Parameters
data
The target object.
predicate
A function that takes the value, key, and the data itself
and returns `true` if the entry shouldn't be part of the output object, or
`false` to keep it. If the function is a type-guard on the value the output
type would be narrowed accordingly.
Iterates over the entries of data and reconstructs the object using only
entries that predicate accepts. Symbol keys are not passed to the predicate
and would be filtered out from the output object.
See omitBy for a complementary function which starts with a shallow copy of
the input object and removes the entries that the predicate rejects. Because
it is subtractive symbol keys would be copied over to the output object.
See also entries, filter, and fromEntries which could be used to build
your own version of pickBy if you need more control (though the resulting
type might be less precise).
Data First
pickBy(data, predicate);
Parameters
data
The target object.
predicate
A function that takes the value, key, and the data itself
and returns true if the entry should be part of the output object, or `false`
to remove it. If the function is a type-guard on the value the output type
would be narrowed accordingly.
A function that takes the value, key, and the data itself
and returns true if the entry should be part of the output object, or `false`
to remove it. If the function is a type-guard on the value the output type
would be narrowed accordingly.
Gets the value of the given property from an object. Nested properties can
be accessed by providing a variadic array of keys that define the path from
the root to the desired property. Arrays can be accessed by using numeric
keys. Unions and optional properties are handled gracefully by returning
undefined early for any non-existing property on the path. Paths are
validated against the object type to provide stronger type safety, better
compile-time errors, and to enable autocompletion in IDEs.
To check whether a key exists on the object, use hasProp.
Data First
prop(data, ...keys);
Parameters
data
The object or array to access.
key
The key(s) for the property to extract.
Returns
Object
prop({ foo: { bar: "baz" } }, "foo"); //=> { bar: 'baz' }prop({ foo: { bar: "baz" } }, "foo", "bar"); //=> 'baz'prop(["cat", "dog"], 1); //=> 'dog'
Data Last
prop(...keys)(data);
Parameters
key
The key(s) for the property to extract.
Returns
Object
pipe({ foo: { bar: "baz" } }, prop("foo")); //=> { bar: 'baz' }pipe({ foo: { bar: "baz" } }, prop("foo", "bar")); //=> 'baz'pipe(["cat", "dog"], prop(1)); //=> 'dog'
pullObject
Object
Creates an object that maps the result of valueExtractor with a key
resulting from running keyExtractor on each item in data. Duplicate keys
are overwritten, guaranteeing that the extractor functions are run on each
item in data.
There are several other functions that could be used to build an object from
an array:
fromKeys - Builds an object from an array of keys and a mapper for values.
indexBy - Builds an object from an array of values and a mapper for keys.
fromEntries - Builds an object from an array of key-value pairs.
Refer to the docs for more details.
Data First
pullObject(data, keyExtractor, valueExtractor);
Parameters
data
The items used to pull/extract the keys and values from.
A stricter wrapper around the Nullish coalescing operator ??
that ensures that the fallback matches the type of the data. Only works
when data can be null or undefined.
Notice that Number.NaN is not nullish and would not result in returning the
fallback!
Data First
defaultTo(data, fallback);
Parameters
data
A nullish value.
fallback
A value of the same type as `data` that would be returned
when `data` is nullish.
Returns
Object
defaultTo("hello" as string | undefined, "world"); //=> "hello"defaultTo(undefined as string | undefined, "world"); //=> "world"
Data Last
defaultTo(fallback)(data);
Parameters
fallback
A value of the same type as `data` that would be returned
when `data` is nullish.
Returns
Object
pipe("hello" as string | undefined, defaultTo("world")); //=> "hello"pipe(undefined as string | undefined, defaultTo("world")); //=> "world"
tap
Other
Calls the given function with the given value, then returns the given value.
The return value of the provided function is ignored.
This allows "tapping into" a function sequence in a pipe, to perform side
effects on intermediate results.
Data First
tap(value, fn);
Parameters
value
The value to pass into the function.
fn
The function to call.
Returns
Object
tap("foo", console.log); // => "foo"
Data Last
tap(fn)(value);
Parameters
fn
The function to call.
Returns
Object
pipe( [-5, -1, 2, 3], filter((n) => n > 0), tap(console.log), // prints [2, 3] map((n) => n * 2),); // => [4, 6]
string
capitalize
String
Makes the first character of a string uppercase while leaving the rest
unchanged.
For display purposes, prefer using the CSS pseudo-element ::first-letter to target
just the first letter of the word, and text-transform: uppercase
to capitalize it. This transformation is locale-aware.
Determines whether a string ends with the provided suffix, and refines the
output type if possible.
This function is a wrapper around the built-in String.prototype.endsWith
method, but doesn't expose the endPosition parameter. To check only up to a
specific position, use endsWith(sliceString(data, 0, endPosition), suffix).
The pattern describing where each split should occur. Can
be a string, or a regular expression.
limit
A non-negative integer specifying a limit on the number of
substrings to be included in the array. If provided, splits the string at
each occurrence of the specified separator, but stops when limit entries have
been placed in the array. Any leftover text is not included in the array at
all. The array may contain fewer entries than limit if the end of the string
is reached before the limit is reached. If limit is 0, [] is returned.
The pattern describing where each split should occur. Can
be a string, or a regular expression.
limit
A non-negative integer specifying a limit on the number of
substrings to be included in the array. If provided, splits the string at
each occurrence of the specified separator, but stops when limit entries have
been placed in the array. Any leftover text is not included in the array at
all. The array may contain fewer entries than limit if the end of the string
is reached before the limit is reached. If limit is 0, [] is returned.
Determines whether a string begins with the provided prefix, and refines the
output type if possible.
This function is a wrapper around the built-in String.prototype.startsWith
method, but doesn't expose the startPosition parameter. To check from a
specific position, use
startsWith(sliceString(data, startPosition), prefix).
Converts text to camelCase by splitting it into words, lowercasing the
first word, capitalizing the rest, then joining them back together.
Because it uses the built-in case conversion methods, the function shares
their locale inaccuracies
too, making it best suited for simple strings like identifiers and internal
keys. For linguistic text processing, use Intl.Segmenter
with granularity: "word",
toLocaleLowerCase,
and toLocaleUpperCase
which are purpose-built to handle nuances in languages and locales.
An _optional_ object with the _optional_ property
`preserveConsecutiveUppercase` that can be used to change the way consecutive
uppercase characters are handled. Defaults to `true`.
An _optional_ object with the _optional_ property
`preserveConsecutiveUppercase` that can be used to change the way consecutive
uppercase characters are handled. Defaults to `true`.
Converts text to kebab-case by splitting it into words and joining them
back together with hyphens (-), then lowercasing the result.
Because it uses toLowerCase,
the function shares its locale inaccuracies
too, making it best suited for simple strings like identifiers and internal
keys. For linguistic text processing, use Intl.Segmenter
with granularity: "word", and
toLocaleLowerCase,
which are purpose-built to handle nuances in languages and locales.
Converts text to snake_case by splitting it into words and joining them
back together with underscores (_), then lowercasing the result.
Because it uses toLowerCase,
the function shares its locale inaccuracies
too, making it best suited for simple strings like identifiers and internal
keys. For linguistic text processing, use Intl.Segmenter
with granularity: "word", and
toLocaleLowerCase,
which are purpose-built to handle nuances in languages and locales.
Converts text to Title Case by splitting it into words, capitalizing the
first letter of each word, then joining them back together with spaces.
Because it uses the built-in case conversion methods, the function shares
their locale inaccuracies,
making it best suited for simple strings like identifiers and internal keys.
For linguistic text processing, use Intl.Segmenter
with granularity: "word",
toLocaleLowerCase,
and toLocaleUpperCase
which are purpose-built to handle nuances in languages and locales.
An _optional_ object with the _optional_ property
`preserveConsecutiveUppercase` that can be used to change the way consecutive
uppercase characters are handled. Defaults to `true`.
An _optional_ object with the _optional_ property
`preserveConsecutiveUppercase` that can be used to change the way consecutive
uppercase characters are handled. Defaults to `true`.
Truncates strings to a maximum length, adding an ellipsis when truncated.
Shorter strings are returned unchanged. If the omission marker is longer than
the maximum length, it will be truncated as well.
The separator argument provides more control by optimistically searching
for a matching cutoff point, which could be used to avoid truncating in the
middle of a word or other semantic boundary.
If you just need to limit the total length of the string, without adding an
omission or optimizing the cutoff point via separator, prefer
sliceString instead, which runs more efficiently.
The function counts Unicode characters, not visual graphemes, and may split
emojis, denormalized diacritics, or combining characters, in the middle. For
display purposes, prefer CSS text-overflow: ellipsis
which is locale-aware and purpose-built for this task.
Data First
truncate(data, n, { omission, separator });
Parameters
data
The input string.
n
The maximum length of the output string. The output will **never**
exceed this length.
For display purposes, prefer using the CSS pseudo-element ::first-letter to target
just the first letter of the word, and text-transform: lowercase
to lowercase it. This transformation is locale-aware.
A utility to allow JSONPath-like strings to be used in other utilities which
take an array of path segments as input (e.g. prop, setPath, etc...).
The main purpose of this utility is to act as a bridge between the runtime
implementation that converts the path to an array, and the type-system that
parses the path string type into an array type. This type allows us
to return fine-grained types and to enforce correctness at the type-level.
We discourage using this utility for new code. This utility is for legacy
code that already contains path strings (which are accepted by Lodash). We
strongly recommend using path arrays instead as they provide better
developer experience via significantly faster type-checking, fine-grained
error messages, and automatic typeahead suggestions for each segment of the
path.
There are a bunch of limitations to this utility derived from the
limitations of the type itself, these are usually edge-cases around deeply
nested paths, escaping, whitespaces, and empty segments. This is true even
in cases where the runtime implementation can better handle them, this is
intentional. See the tests for this utility for more details and the
expected outputs.