Functions

List of all functions from perkakas

add

Number

Adds two numbers.

Data First

P.add(value, addend);
P.add(10, 5); // => 15
P.add(10, -5); // => 5
P.reduce([1, 2, 3, 4], P.add, 0); // => 10

Data Last

P.add(addend)(value);
P.add(5)(10); // => 15
P.add(-5)(10); // => 5
P.map([1, 2, 3, 4], P.add(1)); // => [2, 3, 4, 5]

addProp

Object

Add a new property to an object.

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.

Data First

P.addProp(obj, prop, value);
P.addProp({ firstName: 'john' }, 'lastName', 'doe'); // => {firstName: 'john', lastName: 'doe'}

Data Last

P.addProp(prop, value)(obj);
P.addProp('lastName', 'doe')({ firstName: 'john' }); // => {firstName: 'john', lastName: 'doe'}

allPass

Array

Determines whether all predicates returns true for the input data.

Data First

P.allPass(data, fns);
const isDivisibleBy3 = (x: number) => x % 3 === 0;
const isDivisibleBy4 = (x: number) => x % 4 === 0;
const fns = [isDivisibleBy3, isDivisibleBy4];
P.allPass(12, fns); // => true
P.allPass(8, fns); // => false

Data Last

P.allPass(fns)(data);
const isDivisibleBy3 = (x: number) => x % 3 === 0;
const isDivisibleBy4 = (x: number) => x % 4 === 0;
const fns = [isDivisibleBy3, isDivisibleBy4];
P.allPass(fns)(12); // => true
P.allPass(fns)(8); // => false

anyPass

Array

Determines whether any predicate returns true for the input data.

Data First

P.anyPass(data, fns);
const isDivisibleBy3 = (x: number) => x % 3 === 0;
const isDivisibleBy4 = (x: number) => x % 4 === 0;
const fns = [isDivisibleBy3, isDivisibleBy4];
P.anyPass(8, fns); // => true
P.anyPass(11, fns); // => false

Data Last

P.anyPass(fns)(data);
const isDivisibleBy3 = (x: number) => x % 3 === 0;
const isDivisibleBy4 = (x: number) => x % 4 === 0;
const fns = [isDivisibleBy3, isDivisibleBy4];
P.anyPass(fns)(8); // => true
P.anyPass(fns)(11); // => false

ceil

Number

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

P.ceil(value, precision);
P.ceil(123.9876, 3); // => 123.988
P.ceil(483.22243, 1); // => 483.3
P.ceil(8541, -1); // => 8550
P.ceil(456789, -3); // => 457000

Data Last

P.ceil(precision)(value);
P.ceil(3)(123.9876); // => 123.988
P.ceil(1)(483.22243); // => 483.3
P.ceil(-1)(8541); // => 8550
P.ceil(-3)(456789); // => 457000

chunk

Array

Split an array into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements.

Data First

P.chunk(array, size);
P.chunk(['a', 'b', 'c', 'd'], 2); // => [['a', 'b'], ['c', 'd']]
P.chunk(['a', 'b', 'c', 'd'], 3); // => [['a', 'b', 'c'], ['d']]

Data Last

P.chunk(size)(array);
P.chunk(2)(['a', 'b', 'c', 'd']); // => [['a', 'b'], ['c', 'd']]
P.chunk(3)(['a', 'b', 'c', 'd']); // => [['a', 'b', 'c'], ['d']]

clamp

Number

Clamp the given value within the inclusive min and max bounds.

Data First

P.clamp(value, { min, max });
clamp(10, { min: 20 }); // => 20
clamp(10, { max: 5 }); // => 5
clamp(10, { max: 20, min: 5 }); // => 10

Data Last

P.clamp({ min, max })(value);
clamp({ min: 20 })(10); // => 20
clamp({ max: 5 })(10); // => 5
clamp({ max: 20, min: 5 })(10); // => 10

clone

Object

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

P.clone(data);
P.clone({ foo: 'bar' }); // {foo: 'bar'}

Data Last

P.clone()(data);
P.pipe({ foo: 'bar' }, P.clone()); // {foo: 'bar'}

concat

Array

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

P.concat(data, other);
P.concat([1, 2, 3], ['a']); // [1, 2, 3, 'a']

Data Last

P.concat(arr2)(arr1);
P.concat(['a'])([1, 2, 3]); // [1, 2, 3, 'a']

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.

!IMPORTANT! - Unlike similar implementations in frameworks like Lodash and Ramda, this implementation does NOT return a default/fallback undefined value when none of the cases match; and instead will throw an exception in those cases. To add a default case use the conditional.defaultCase helper as the final case of your implementation. By default it returns undefined, but could be provided a transformer in order to return something else.

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.

Data Last

P.conditional(...cases)(data);
const nameOrId = 3 as string | number;
P.pipe(
    nameOrId,
    P.conditional(
        [P.isString, (name) => `Hello ${name}`],
        [P.isNumber, (id) => `Hello ID: ${id}`],
        P.conditional.defaultCase(
            (something) => `Hello something (${JSON.stringify(something)})`,
        ),
    ),
); //=> 'Hello ID: 3'

Data First

P.conditional(data, ...cases);
const nameOrId = 3 as string | number;
P.conditional(
    nameOrId,
    [P.isString, (name) => `Hello ${name}`],
    [P.isNumber, (id) => `Hello ID: ${id}`],
    P.conditional.defaultCase(
        (something) => `Hello something (${JSON.stringify(something)})`,
    ),
); //=> 'Hello ID: 3'

constant

Function

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

P.constant(value);
P.map([1, 2, 3], P.constant('a')); // => ['a', 'a', 'a']
P.map([1, 2, 3], isDemoMode ? P.add(1) : P.constant(0)); // => [2, 3, 4] or [0, 0, 0]

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.

Data First

P.countBy(data, categorizationFn);
P.countBy(['a', 'b', 'c', 'B', 'A', 'a'], toLowerCase); //=> { a: 3, b: 2, c: 1 }

Data Last

P.countBy(categorizationFn)(data);
P.pipe(['a', 'b', 'c', 'B', 'A', 'a'], P.countBy(toLowerCase)); //=> { a: 3, b: 2, c: 1 }

curry

Function

Creates a function with dataFirst and dataLast signatures.

curry 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 curry 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!

P.curry(fn, args);
function _findIndex(array, fn) {
    for (let i = 0; i < array.length; i++) {
        if (fn(array[i])) {
            return i;
        }
    }
    return -1;
}

// data-first
function findIndex<T>(array: T[], fn: (item: T) => boolean): number;

// data-last
function findIndex<T>(fn: (item: T) => boolean): (array: T[]) => number;

function findIndex(...args: unknown[]) {
    return P.curry(_findIndex, args);
}

debounce

Function

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.

Data First

P.debounce(func, options);
const debouncer = debounce(identity(), { timing: 'trailing', waitMs: 1000 });
const result1 = debouncer.call(1); // => undefined
const result2 = debouncer.call(2); // => undefined
// after 1 second
const result3 = debouncer.call(3); // => 2
// after 1 second
debouncer.cachedValue; // => 3

difference

Array

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).

Data First

P.difference(data, other);
P.difference([1, 2, 3, 4], [2, 5, 3]); // => [1, 4]
P.difference([1, 1, 2, 2], [1]); // => [1, 2, 2]

Data First

P.difference(other)(data);
P.pipe([1, 2, 3, 4], P.difference([2, 5, 3])); // => [1, 4]
P.pipe([1, 1, 2, 2], P.difference([1])); // => [1, 2, 2]

differenceWith

Array

Excludes the values from other array. Elements are compared by custom comparator isEquals.

Data First

P.differenceWith(array, other, isEquals);
P.differenceWith(
    [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }],
    [{ a: 2 }, { a: 5 }, { a: 3 }],
    P.equals,
); // => [{a: 1}, {a: 4}]

Data Last

P.differenceWith(other, isEquals)(array);
P.differenceWith(
    [{ a: 2 }, { a: 5 }, { a: 3 }],
    P.equals,
)([{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }]); // => [{a: 1}, {a: 4}]
P.pipe(
    [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }, { a: 5 }, { a: 6 }], // only 4 iterations
    P.differenceWith([{ a: 2 }, { a: 3 }], P.equals),
    P.take(2),
); // => [{a: 1}, {a: 4}]

divide

Number

Divides two numbers.

Data First

P.divide(value, divisor);
P.divide(12, 3); // => 4
P.reduce([1, 2, 3, 4], P.divide, 24); // => 1

Data Last

P.divide(divisor)(value);
P.divide(3)(12); // => 4
P.map([2, 4, 6, 8], P.divide(2)); // => [1, 2, 3, 4]

doNothing

Function

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.

Data Last

P.doNothing();
myApi({ onSuccess: handleSuccess, onError: P.doNothing() });
myApi({ onSuccess: isDemoMode ? P.doNothing() : handleSuccess });

drop

Array

Removes first n elements from the array.

Data First

P.drop(array, n);
P.drop([1, 2, 3, 4, 5], 2); // => [3, 4, 5]

Data Last

P.drop(n)(array);
P.drop(2)([1, 2, 3, 4, 5]); // => [3, 4, 5]

dropFirstBy

Array

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

P.dropFirstBy(data, n, ...rules);
P.dropFirstBy(['aa', 'aaaa', 'a', 'aaa'], 2, (x) => x.length); // => ['aaa', 'aaaa']

Data Last

P.dropFirstBy(n, ...rules)(data);
P.pipe(
    ['aa', 'aaaa', 'a', 'aaa'],
    P.dropFirstBy(2, (x) => x.length),
); // => ['aaa', 'aaaa']

dropLast

Array

Removes last n elements from the array.

Data First

P.dropLast(array, n);
P.dropLast([1, 2, 3, 4, 5], 2); // => [1, 2, 3]

Data Last

P.dropLast(n)(array);
P.dropLast(2)([1, 2, 3, 4, 5]); // => [1, 2, 3]

dropLastWhile

Array

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.

Data First

P.dropLastWhile(data, predicate);
P.dropLastWhile([1, 2, 10, 3, 4], (x) => x < 10); // => [1, 2, 10]

Data Last

P.dropLastWhile(predicate)(data);
P.pipe(
    [1, 2, 10, 3, 4],
    P.dropLastWhile((x) => x < 10),
); // => [1, 2, 10]

dropWhile

Array

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.

Data First

P.dropWhile(data, predicate);
P.dropWhile([1, 2, 10, 3, 4], (x) => x < 10); // => [10, 3, 4]

Data Last

P.dropWhile(predicate)(data);
P.pipe(
    [1, 2, 10, 3, 4],
    P.dropWhile((x) => x < 10),
); // => [10, 3, 4]

entries

Object

Returns an array of key/values of the enumerable properties of an object.

Data First

P.entries(object);
P.entries({ a: 1, b: 2, c: 3 }); // => [['a', 1], ['b', 2], ['c', 3]]

Data Last

P.entries()(object);
P.pipe({ a: 1, b: 2, c: 3 }, P.entries()); // => [['a', 1], ['b', 2], ['c', 3]]

evolve

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

P.evolve(data, evolver);
const evolver = {
    count: add(1),
    time: { elapsed: add(1), remaining: add(-1) },
};
const data = {
    id: 10,
    count: 10,
    time: { elapsed: 100, remaining: 1400 },
};
evolve(data, evolver);
// => {
//   id: 10,
//   count: 11,
//   time: { elapsed: 101, remaining: 1399 },
// }

Data Last

P.evolve(evolver)(data);
const evolver = {
    count: add(1),
    time: { elapsed: add(1), remaining: add(-1) },
};
const data = {
    id: 10,
    count: 10,
    time: { elapsed: 100, remaining: 1400 },
};
P.pipe(object, P.evolve(evolver));
// => {
//   id: 10,
//   count: 11,
//   time: { elapsed: 101, remaining: 1399 },
// }

filter

Array

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

P.filter(data, predicate);
P.filter([1, 2, 3], (x) => x % 2 === 1); // => [1, 3]

Data Last

P.filter(predicate)(data);
P.pipe(
    [1, 2, 3],
    P.filter((x) => x % 2 === 1),
); // => [1, 3]

find

Array

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

P.find(data, predicate);
P.find([1, 3, 4, 6], (n) => n % 2 === 0); // => 4

Data Last

P.find(predicate)(data);
P.pipe(
    [1, 3, 4, 6],
    P.find((n) => n % 2 === 0),
); // => 4

findIndex

Array

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

P.findIndex(data, predicate);
P.findIndex([1, 3, 4, 6], (n) => n % 2 === 0); // => 2

Data Last

P.findIndex(predicate)(data);
P.pipe(
    [1, 3, 4, 6],
    P.findIndex((n) => n % 2 === 0),
); // => 2

findLast

Array

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

P.findLast(data, predicate);
P.findLast([1, 3, 4, 6], (n) => n % 2 === 1); // => 3

Data Last

P.findLast(predicate)(data);
P.pipe(
    [1, 3, 4, 6],
    P.findLast((n) => n % 2 === 1),
); // => 3

findLastIndex

Array

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

P.findLastIndex(data, predicate);
P.findLastIndex([1, 3, 4, 6], (n) => n % 2 === 1); // => 1

Data Last

P.findLastIndex(fn)(items);
P.pipe(
    [1, 3, 4, 6],
    P.findLastIndex((n) => n % 2 === 1),
); // => 1

first

Array

Gets the first element of array.

Data First

P.first(array);
P.first([1, 2, 3]); // => 1
P.first([]); // => undefined

Data Last

P.first()(array);
P.pipe(
    [1, 2, 4, 8, 16],
    P.filter((x) => x > 3),
    P.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 P.first(P.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 Last

P.firstBy(...rules)(data);
const max = P.pipe([1, 2, 3], P.firstBy([P.identity(), 'desc'])); // => 3;
const min = P.pipe([1, 2, 3], P.firstBy(P.identity())); // => 1;

const data = [{ a: 'a' }, { a: 'aa' }, { a: 'aaa' }] as const;
const maxBy = P.pipe(data, P.firstBy([(item) => item.a.length, 'desc'])); // => { a: "aaa" };
const minBy = P.pipe(
    data,
    P.firstBy((item) => item.a.length),
); // => { a: "a" };

const data = [
    { type: 'cat', size: 1 },
    { type: 'cat', size: 2 },
    { type: 'dog', size: 3 },
] as const;
const multi = P.pipe(data, P.firstBy(P.prop('type'), [P.prop('size'), 'desc'])); // => {type: "cat", size: 2}

Data First

P.firstBy(data, ...rules);
const max = P.firstBy([1, 2, 3], [P.identity(), 'desc']); // => 3;
const min = P.firstBy([1, 2, 3], P.identity()); // => 1;

const data = [{ a: 'a' }, { a: 'aa' }, { a: 'aaa' }] as const;
const maxBy = P.firstBy(data, [(item) => item.a.length, 'desc']); // => { a: "aaa" };
const minBy = P.firstBy(data, (item) => item.a.length); // => { a: "a" };

const data = [
    { type: 'cat', size: 1 },
    { type: 'cat', size: 2 },
    { type: 'dog', size: 3 },
] as const;
const multi = P.firstBy(data, P.prop('type'), [P.prop('size'), 'desc']); // => {type: "cat", size: 2}

flat

Array

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

P.flat(data);
P.flat(data, depth);
P.flat([[1, 2], [3, 4], [5], [[6]]]); // => [1, 2, 3, 4, 5, [6]]
P.flat([[[1]], [[2]]], 2); // => [1, 2]

Data Last

P.flat()(data);
P.flat(depth)(data);
P.pipe([[1, 2], [3, 4], [5], [[6]]], P.flat()); // => [1, 2, 3, 4, 5, [6]]
P.pipe([[[1]], [[2]]], P.flat(2)); // => [1, 2]

flatMap

Array

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

P.flatMap(data, callbackfn);
P.flatMap([1, 2, 3], (x) => [x, x * 10]); // => [1, 10, 2, 20, 3, 30]

Data Last

P.flatMap(callbackfn)(data);
P.pipe(
    [1, 2, 3],
    P.flatMap((x) => [x, x * 10]),
); // => [1, 10, 2, 20, 3, 30]

floor

Number

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

P.floor(value, precision);
P.floor(123.9876, 3); // => 123.987
P.floor(483.22243, 1); // => 483.2
P.floor(8541, -1); // => 8540
P.floor(456789, -3); // => 456000

Data Last

P.floor(precision)(value);
P.floor(3)(123.9876); // => 123.987
P.floor(1)(483.22243); // => 483.2
P.floor(-1)(8541); // => 8540
P.floor(-3)(456789); // => 456000

forEach

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

P.forEach(data, callbackfn);
P.forEach([1, 2, 3], (x) => {
    console.log(x);
});

Data Last

P.forEach(callbackfn)(data);
P.pipe(
    [1, 2, 3],
    P.forEach((x) => {
        console.log(x);
    }),
); // => [1, 2, 3]

forEachObj

Object

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

P.forEachObj(object, fn);
P.forEachObj({ a: 1 }, (val, key, obj) => {
    console.log(`${key}: ${val}`);
}); // "a: 1"

Data Last

P.forEachObj(fn)(object);
P.pipe(
    { a: 1 },
    P.forEachObj((val, key) => console.log(`${key}: ${val}`)),
); // "a: 1"

fromEntries

Object

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.
  • mapToObj: Builds an object from an array of items and a single mapper for key-value pairs. Refer to the docs for more details.

Data First

P.fromEntries(tuples);
P.fromEntries([
    ['a', 'b'],
    ['c', 'd'],
]); // => {a: 'b', c: 'd'}

Data Last

P.fromEntries()(tuples);
P.pipe(
    [
        ['a', 'b'],
        ['c', 'd'],
    ] as const,
    P.fromEntries(),
); // => {a: 'b', c: 'd'}

fromKeys

Object

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. mapToObj - Builds an object from an array of items and a single mapper for key-value pairs. Refer to the docs for more details.

Data First

P.fromKeys(data, mapper);
P.fromKeys(['cat', 'dog'], P.length()); // { cat: 3, dog: 3 } (typed as Partial<Record<"cat" | "dog", number>>)
P.fromKeys([1, 2], P.add(1)); // { 1: 2, 2: 3 } (typed as Partial<Record<1 | 2, number>>)

Data Last

P.fromKeys(mapper)(data);
P.pipe(['cat', 'dog'], P.fromKeys(P.length())); // { cat: 3, dog: 3 } (typed as Partial<Record<"cat" | "dog", number>>)
P.pipe([1, 2], P.fromKeys(P.add(1))); // { 1: 2, 2: 3 } (typed as Partial<Record<1 | 2, number>>)

funnel

Function

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".
  • Batching: See the reference implementation in funnel.reference-batch.test.ts.

P.funnel(callback, options);
const debouncer = P.funnel(
    () => {
        console.log('Callback executed!');
    },
    { minQuietPeriodMs: 100 },
);
debouncer.call();
debouncer.call();

const throttle = P.funnel(
    () => {
        console.log('Callback executed!');
    },
    { minGapMs: 100, triggerAt: 'start' },
);
throttle.call();
throttle.call();

groupBy

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.

Data First

P.groupBy(data, callbackfn);
P.groupBy([{ a: 'cat' }, { a: 'dog' }] as const, P.prop('a')); // => {cat: [{a: 'cat'}], dog: [{a: 'dog'}]}
P.groupBy([0, 1], (x) => (x % 2 === 0 ? 'even' : undefined)); // => {even: [0]}

Data Last

P.groupBy(callbackfn)(data);
P.pipe([{ a: 'cat' }, { a: 'dog' }] as const, P.groupBy(P.prop('a'))); // => {cat: [{a: 'cat'}], dog: [{a: 'dog'}]}
P.pipe(
    [0, 1],
    P.groupBy((x) => (x % 2 === 0 ? 'even' : undefined)),
); // => {even: [0]}

hasAtLeast

Array

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

P.hasAtLeast(data, minimum);
P.hasAtLeast([], 4); // => false

const data: number[] = [1, 2, 3, 4];
P.hasAtLeast(data, 1); // => true
data[0]; // 1, with type `number`

Data Last

P.hasAtLeast(minimum)(data);
P.pipe([], P.hasAtLeast(4)); // => false

const data = [[1, 2], [3], [4, 5]];
P.pipe(
    data,
    P.filter(P.hasAtLeast(2)),
    P.map(([, second]) => second),
); // => [2,5], with type `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.

Data First

P.hasSubObject(data, subObject);
P.hasSubObject({ a: 1, b: 2, c: 3 }, { a: 1, c: 3 }); //=> true
P.hasSubObject({ a: 1, b: 2, c: 3 }, { b: 4 }); //=> false
P.hasSubObject({ a: 1, b: 2, c: 3 }, {}); //=> true

Data Last

P.hasSubObject(subObject)(data);
P.hasSubObject({ a: 1, c: 3 })({ a: 1, b: 2, c: 3 }); //=> true
P.hasSubObject({ b: 4 })({ a: 1, b: 2, c: 3 }); //=> false
P.hasSubObject({})({ a: 1, b: 2, c: 3 }); //=> true

humanReadableFileSize

String

Returns human readable file size.

P.humanReadableFileSize(bytes, base);
P.humanReadableFileSize(1000); // => '1.0 kB'
P.humanReadableFileSize(2097152, 1024); // => '2.0 Mib'

identity

Function

A function that returns the first argument passed to it.

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. constant - A function that ignores the input arguments and returns the same value on every invocation.

P.identity();
P.map([1, 2, 3], P.identity()); // => [1,2,3]

indexBy

Array

Converts a list of objects into an object indexing the objects by the given key.

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. 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. mapToObj - Builds an object from an array of items and a single mapper for key-value pairs. Refer to the docs for more details.

Data First

P.indexBy(array, fn);
P.indexBy(['one', 'two', 'three'], (x) => x.length); // => {3: 'two', 5: 'three'}

Data Last

P.indexBy(fn)(array);
P.pipe(
    ['one', 'two', 'three'],
    P.indexBy((x) => x.length),
); // => {3: 'two', 5: 'three'}

intersection

Array

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).

Data First

P.intersection(data, other);
P.intersection([1, 2, 3], [2, 3, 5]); // => [2, 3]
P.intersection([1, 1, 2, 2], [1]); // => [1]

Data First

P.intersection(other)(data);
P.pipe([1, 2, 3], P.intersection([2, 3, 5])); // => [2, 3]
P.pipe([1, 1, 2, 2], P.intersection([1])); // => [1]

intersectionWith

Array

Returns a list of intersecting values based on a custom comparator function that compares elements of both arrays.

Data First

P.intersectionWith(array, other, comparator);
P.intersectionWith(
    [
        { id: 1, name: 'Ryan' },
        { id: 3, name: 'Emma' },
    ],
    [3, 5],
    (a, b) => a.id === b,
); // => [{ id: 3, name: 'Emma' }]

Data Last

P.intersectionWith(other, comparator)(array);
P.intersectionWith(
    [3, 5],
    (a, b) => a.id === b,
)([
    { id: 1, name: 'Ryan' },
    { id: 3, name: 'Emma' },
]); // => [{ id: 3, name: 'Emma' }]

invert

Object

Returns an object whose keys and values are swapped. If the object contains duplicate values, subsequent values will overwrite previous values.

Data First

P.invert(object);
P.invert({ a: 'd', b: 'e', c: 'f' }); // => { d: "a", e: "b", f: "c" }

Data Last

P.invert()(object);
P.pipe({ a: 'd', b: 'e', c: 'f' }, P.invert()); // => { d: "a", e: "b", f: "c" }

isArray

Guard

A function that checks if the passed parameter is an Array and narrows its type accordingly.

P.isArray(data);
P.isArray([5]); //=> true
P.isArray([]); //=> true
P.isArray('somethingElse'); //=> false

isBigInt

Guard

A function that checks if the passed parameter is a bigint and narrows its type accordingly.

P.isBigInt(data);
P.isBigInt(1n); // => true
P.isBigInt(1); // => false
P.isBigInt('notANumber'); // => false

isBoolean

Guard

A function that checks if the passed parameter is a boolean and narrows its type accordingly.

P.isBoolean(data);
P.isBoolean(true); //=> true
P.isBoolean(false); //=> true
P.isBoolean('somethingElse'); //=> false

isDate

Guard

A function that checks if the passed parameter is a Date and narrows its type accordingly.

P.isDate(data);
P.isDate(new Date()); //=> true
P.isDate('somethingElse'); //=> false

isDeepEqual

Guard

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.

!IMPORTANT: TypedArrays and symbol properties of objects are not supported right now and might result in unexpected behavior.

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.

Data First

P.isDeepEqual(data, other);
P.isDeepEqual(1, 1); //=> true
P.isDeepEqual(1, '1'); //=> false
P.isDeepEqual([1, 2, 3], [1, 2, 3]); //=> true

Data Last

P.isDeepEqual(other)(data);
P.pipe(1, P.isDeepEqual(1)); //=> true
P.pipe(1, P.isDeepEqual('1')); //=> false
P.pipe([1, 2, 3], P.isDeepEqual([1, 2, 3])); //=> true

isDefined

Guard

A function that checks if the passed parameter is defined (!== undefined) and narrows its type accordingly.

P.isDefined(data);
P.isDefined('string'); //=> true
P.isDefined(null); //=> true
P.isDefined(undefined); //=> false

isEmpty

Guard

A function that checks if the passed parameter is empty.

undefined is also considered empty, but only when it's in a union with a string or string-like type.

This guard doesn't work negated because of typescript limitations! If you need to check that an array is not empty, use P.hasAtLeast(data, 1) and not !P.isEmpty(data). For strings and objects there's no way in typescript to narrow the result to a non-empty type.

P.isEmpty(data);
P.isEmpty(undefined); //=>true
P.isEmpty(''); //=> true
P.isEmpty([]); //=> true
P.isEmpty({}); //=> true
P.isEmpty('test'); //=> false
P.isEmpty([1, 2, 3]); //=> false
P.isEmpty({ length: 0 }); //=> false

isError

Guard

A function that checks if the passed parameter is an Error and narrows its type accordingly.

P.isError(data);
P.isError(new Error('message')); //=> true
P.isError('somethingElse'); //=> false

isFunction

Guard

A function that checks if the passed parameter is a Function and narrows its type accordingly.

P.isFunction(data);
P.isFunction(() => {}); //=> true
P.isFunction('somethingElse'); //=> false

isIncludedIn

Guard

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.

Data First

P.isIncludedIn(data, container);
P.isIncludedIn(2, [1, 2, 3]); // => true
P.isIncludedIn(4, [1, 2, 3]); // => false

const data = 'cat' as 'cat' | 'dog' | 'mouse';
P.isIncludedIn(data, ['cat', 'dog'] as const); // true (typed "cat" | "dog");

Data Last

P.isIncludedIn(container)(data);
P.pipe(2, P.isIncludedIn([1, 2, 3])); // => true
P.pipe(4, P.isIncludedIn([1, 2, 3])); // => false

const data = 'cat' as 'cat' | 'dog' | 'mouse';
P.pipe(data, P.isIncludedIn(['cat', 'dog'] as const)); // => true (typed "cat" | "dog");

isNonNull

Guard

A function that checks if the passed parameter is not null and narrows its type accordingly. Notice that undefined is not null!

P.isNonNull(data);
P.isNonNull('string'); //=> true
P.isNonNull(null); //=> false
P.isNonNull(undefined); //=> true

isNonNullish

Guard

A function that checks if the passed parameter is defined AND isn't null and narrows its type accordingly.

P.isNonNullish(data);
P.isNonNullish('string'); //=> true
P.isNonNullish(null); //=> false
P.isNonNullish(undefined); //=> false

isNot

Guard

A function that takes a guard function as predicate and returns a guard that negates it.

Data Last

P.isNot(P.isTruthy)(data);
P.isNot(P.isTruthy)(false); //=> true
P.isNot(P.isTruthy)(true); //=> false

isNullish

Guard

A function that checks if the passed parameter is either null or undefined and narrows its type accordingly.

P.isNullish(data);
P.isNullish(undefined); //=> true
P.isNullish(null); //=> true
P.isNullish('somethingElse'); //=> false

isNumber

Guard

A function that checks if the passed parameter is a number and narrows its type accordingly.

P.isNumber(data);
P.isNumber(1); // => true
P.isNumber(1n); // => false
P.isNumber('notANumber'); // => false

isObjectType

Guard

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

P.isObjectType(data);
// true
P.isObjectType({}); //=> true
P.isObjectType([]); //=> true
P.isObjectType(Promise.resolve('something')); //=> true
P.isObjectType(new Date()); //=> true
P.isObjectType(new Error('error')); //=> true

// false
P.isObjectType('somethingElse'); //=> false
P.isObjectType(null); //=> false

isPlainObject

Guard

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.

P.isPlainObject(data);
// true
P.isPlainObject({}); //=> true
P.isPlainObject({ a: 123 }); //=> true

// false
P.isPlainObject([]); //=> false
P.isPlainObject(Promise.resolve('something')); //=> false
P.isPlainObject(new Date()); //=> false
P.isPlainObject(new Error('error')); //=> false
P.isPlainObject('somethingElse'); //=> false
P.isPlainObject(null); //=> false

isPromise

Guard

A function that checks if the passed parameter is a Promise and narrows its type accordingly.

P.isPromise(data);
P.isPromise(Promise.resolve(5)); //=> true
P.isPromise(Promise.reject(5)); //=> true
P.isPromise('somethingElse'); //=> false

isShallowEqual

Guard

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: 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.

Data First

P.isShallowEqual(data, other);
P.isShallowEqual(1, 1); //=> true
P.isShallowEqual(1, '1'); //=> false
P.isShallowEqual([1, 2, 3], [1, 2, 3]); //=> true
P.isShallowEqual([[1], [2], [3]], [[1], [2], [3]]); //=> false

Data First

P.isShallowEqual(other)(data);
P.pipe(1, P.isShallowEqual(1)); //=> true
P.pipe(1, P.isShallowEqual('1')); //=> false
P.pipe([1, 2, 3], P.isShallowEqual([1, 2, 3])); //=> true
P.pipe([[1], [2], [3]], P.isShallowEqual([[1], [2], [3]])); //=> false

isStrictEqual

Guard

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.

Data First

P.isStrictEqual(data, other);
P.isStrictEqual(1, 1); //=> true
P.isStrictEqual(1, '1'); //=> false
P.isStrictEqual([1, 2, 3], [1, 2, 3]); //=> false

Data Last

P.isStrictEqual(other)(data);
P.pipe(1, P.isStrictEqual(1)); //=> true
P.pipe(1, P.isStrictEqual('1')); //=> false
P.pipe([1, 2, 3], P.isStrictEqual([1, 2, 3])); //=> false

isString

Guard

A function that checks if the passed parameter is a string and narrows its type accordingly.

P.isString(data);
P.isString('string'); //=> true
P.isString(1); //=> false

isSymbol

Guard

A function that checks if the passed parameter is a symbol and narrows its type accordingly.

P.isSymbol(data);
P.isSymbol(Symbol('foo')); //=> true
P.isSymbol(1); //=> false

isTruthy

Guard

A function that checks if the passed parameter is truthy and narrows its type accordingly.

P.isTruthy(data);
P.isTruthy('somethingElse'); //=> true
P.isTruthy(null); //=> false
P.isTruthy(undefined); //=> false
P.isTruthy(false); //=> false
P.isTruthy(0); //=> false
P.isTruthy(''); //=> false

join

Array

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).

Data First

P.join(data, glue);
P.join([1, 2, 3], ','); // => "1,2,3" (typed `string`)
P.join(['a', 'b', 'c'], ''); // => "abc" (typed `string`)
P.join(['hello', 'world'] as const, ' '); // => "hello world" (typed `hello world`)

Data Last

P.join(glue)(data);
P.pipe([1, 2, 3], P.join(',')); // => "1,2,3" (typed `string`)
P.pipe(['a', 'b', 'c'], P.join('')); // => "abc" (typed `string`)
P.pipe(['hello', 'world'] as const, P.join(' ')); // => "hello world" (typed `hello world`)

keys

Object

Returns a new array containing the keys of the array or object.

Data First

P.keys(source);
P.keys(['x', 'y', 'z']); // => ['0', '1', '2']
P.keys({ a: 'x', b: 'y', 5: 'z' }); // => ['a', 'b', '5']

Data Last

P.keys()(source);
P.Pipe(['x', 'y', 'z'], keys()); // => ['0', '1', '2']
P.pipe({ a: 'x', b: 'y', 5: 'z' } as const, P.keys()); // => ['a', 'b', '5']

last

Array

Gets the last element of array.

Data First

P.last(array);
P.last([1, 2, 3]); // => 3
P.last([]); // => undefined

Data Last

P.last()(array);
P.pipe(
    [1, 2, 4, 8, 16],
    P.filter((x) => x > 3),
    P.last(),
    (x) => x + 1,
); // => 17

length

Array

Counts values of the collection or iterable.

Data First

P.length(array);
P.length([1, 2, 3]); // => 3

Data Last

P.length()(array);
P.pipe([1, 2, 3], P.length()); // => 3

map

Array

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

P.map(data, callbackfn);
P.map([1, 2, 3], P.multiply(2)); // => [2, 4, 6]
P.map([0, 0], P.add(1)); // => [1, 1]
P.map([0, 0], (value, index) => value + index); // => [0, 1]

Data Last

P.map(callbackfn)(data);
P.pipe([1, 2, 3], P.map(P.multiply(2))); // => [2, 4, 6]
P.pipe([0, 0], P.map(P.add(1))); // => [1, 1]
P.pipe(
    [0, 0],
    P.map((value, index) => value + index),
); // => [0, 1]

mapKeys

Object

Maps keys of object and keeps the same values.

Data First

P.mapKeys(object, fn);
P.mapKeys({ a: 1, b: 2 }, (key, value) => key + value); // => { a1: 1, b2: 2 }

Data Last

P.mapKeys(fn)(object);
P.pipe(
    { a: 1, b: 2 },
    P.mapKeys((key, value) => key + value),
); // => { a1: 1, b2: 2 }

mapToObj

Array

Map each element of an array into an object using a defined callback 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. fromEntries - Builds an object from an array of key-value pairs. Refer to the docs for more details.

Data First

P.mapToObj(array, fn);
P.mapToObj([1, 2, 3], (x) => [String(x), x * 2]); // => {1: 2, 2: 4, 3: 6}

Data Last

P.mapToObj(fn)(array);
P.pipe(
    [1, 2, 3],
    P.mapToObj((x) => [String(x), x * 2]),
); // => {1: 2, 2: 4, 3: 6}

mapValues

Object

Maps values of object and keeps the same keys. Symbol keys are not passed to the mapper and will be removed from the output object.

To also copy the symbol keys to the output use merge: merge(data, mapValues(data, mapper))).

Data First

P.mapValues(data, mapper);
P.mapValues({ a: 1, b: 2 }, (value, key) => value + key); // => {a: '1a', b: '2b'}

Data Last

P.mapValues(mapper)(data);
P.pipe(
    { a: 1, b: 2 },
    P.mapValues((value, key) => value + key),
); // => {a: '1a', b: '2b'}

mapWithFeedback

Array

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

P.mapWithFeedback(data, callbackfn, initialValue);
P.mapWithFeedback([1, 2, 3, 4, 5], (prev, x) => prev + x, 100); // => [101, 103, 106, 110, 115]

Data Last

P.mapWithFeedback(callbackfn, initialValue)(data);
P.pipe(
    [1, 2, 3, 4, 5],
    P.mapWithFeedback((prev, x) => prev + x, 100),
); // => [101, 103, 106, 110, 115]

meanBy

Array

Returns the mean of the elements of an array using the provided predicate.

Data Last

P.meanBy(fn)(array);
P.pipe(
    [{ a: 5 }, { a: 1 }, { a: 3 }],
    P.meanBy((x) => x.a),
); // 3

Data First

P.meanBy(array, fn);
P.meanBy([{ a: 5 }, { a: 1 }, { a: 3 }], (x) => x.a); // 3

merge

Object

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

P.merge(data, source);
P.merge({ x: 1, y: 2 }, { y: 10, z: 2 }); // => { x: 1, y: 10, z: 2 }

Data Last

P.merge(source)(data);
P.pipe({ x: 1, y: 2 }, P.merge({ y: 10, z: 2 })); // => { x: 1, y: 10, z: 2 }

mergeAll

Array

Merges a list of objects into a single object.

P.mergeAll(objects);
P.mergeAll([{ a: 1, b: 1 }, { b: 2, c: 3 }, { d: 10 }]); // => { a: 1, b: 2, c: 3, d: 10 }

mergeDeep

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 both destination 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

P.mergeDeep(destination, source);
P.mergeDeep({ foo: 'bar', x: 1 }, { foo: 'baz', y: 2 }); // => { foo: 'baz', x: 1, y: 2 }

Data Last

P.mergeDeep(source)(destination);
P.pipe({ foo: 'bar', x: 1 }, P.mergeDeep({ foo: 'baz', y: 2 })); // => { foo: 'baz', x: 1, y: 2 }

multiply

Number

Multiplies two numbers.

Data First

P.multiply(value, multiplicand);
P.multiply(3, 4); // => 12
P.reduce([1, 2, 3, 4], P.multiply, 1); // => 24

Data Last

P.multiply(multiplicand)(value);
P.multiply(4)(3); // => 12
P.map([1, 2, 3, 4], P.multiply(2)); // => [2, 4, 6, 8]

nthBy

Array

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

P.nthBy(data, index, ...rules);
P.nthBy([2, 1, 4, 5, 3], 2, identity()); // => 3

Data Last

P.nthBy(index, ...rules)(data);
P.pipe([2, 1, 4, 5, 3], P.nthBy(2, identity())); // => 3

objOf

Object

Creates an object containing a single key:value pair.

P.objOf(value, key);
P.objOf(10, 'a'); // => { a: 10 }

P.objOf(key)(value);
P.pipe(10, P.objOf('a')); // => { a: 10 }

omit

Object

Returns a partial copy of an object omitting the keys specified.

Data Last

P.omit(names)(obj);
P.pipe({ a: 1, b: 2, c: 3, d: 4 }, P.omit(['a', 'd'])); // => { b: 2, c: 3 }

Data First

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

omitBy

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

P.omitBy(data, predicate);
P.omitBy({ a: 1, b: 2, A: 3, B: 4 }, (val, key) => key.toUpperCase() === key); // => {a: 1, b: 2}

Data Last

P.omitBy(fn)(object);
P.omitBy((val, key) => key.toUpperCase() === key)({ a: 1, b: 2, A: 3, B: 4 }); // => {a: 1, b: 2}

once

Function

Creates a function that is restricted to invoking func once. Repeat calls to the function return the value of the first invocation.

P.once(fn);
const initialize = P.once(createApplication);
initialize();
initialize();
// => `createApplication` is invoked once

only

Array

Returns the first and only element of array, or undefined otherwise.

Data First

P.only(array);
P.only([]); // => undefined
P.only([1]); // => 1
P.only([1, 2]); // => undefined

Data Last

P.only()(array);
P.pipe([], P.only()); // => undefined
P.pipe([1], P.only()); // => 1
P.pipe([1, 2], P.only()); // => undefined

partition

Array

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

P.partition(data, predicate);
P.partition(['one', 'two', 'forty two'], (x) => x.length === 3); // => [['one', 'two'], ['forty two']]

Data Last

P.partition(predicate)(data);
P.pipe(
    ['one', 'two', 'forty two'],
    P.partition((x) => x.length === 3),
); // => [['one', 'two'], ['forty two']]

pathOr

Object

Gets the value at path of object. If the resolved value is null or undefined, the defaultValue is returned in its place.

Data First

P.pathOr(object, array, defaultValue);
P.pathOr({ x: 10 }, ['y'], 2); // 2
P.pathOr({ y: 10 }, ['y'], 2); // 10

Data Last

P.pathOr(array, defaultValue)(object);
P.pipe({ x: 10 }, P.pathOr(['y'], 2)); // 2
P.pipe({ y: 10 }, P.pathOr(['y'], 2)); // 10

pick

Object

Creates an object composed of the picked object properties.

Data Last

P.pick([prop1, prop2])(object);
P.pipe({ a: 1, b: 2, c: 3, d: 4 }, P.pick(['a', 'd'])); // => { a: 1, d: 4 }

Data First

P.pick(object, [prop1, prop2]);
P.pick({ a: 1, b: 2, c: 3, d: 4 }, ['a', 'd']); // => { a: 1, d: 4 }

pickBy

Object

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

P.pickBy(data, predicate);
P.pickBy({ a: 1, b: 2, A: 3, B: 4 }, (val, key) => key.toUpperCase() === key); // => {A: 3, B: 4}

Data Last

P.pickBy(predicate)(data);
P.pipe(
    { a: 1, b: 2, A: 3, B: 4 },
    pickBy((val, key) => key.toUpperCase() === key),
); // => {A: 3, B: 4}

pipe

Function

Perform left-to-right function composition.

Data First

P.pipe(data, op1, op2, op3);
P.pipe(
    [1, 2, 3, 4],
    P.map((x) => x * 2),
    (arr) => [arr[0] + arr[1], arr[2] + arr[3]],
); // => [6, 14]

piped

Function

A dataLast version of pipe that could be used to provide more complex computations to functions that accept a function as a param (like map, filter, groupBy, etc.).

The first function must be always annotated. Other functions are automatically inferred.

P.piped(...ops)(data);
P.filter(
    [{ a: 1 }, { a: 2 }, { a: 3 }],
    P.piped(P.prop('a'), (x) => x % 2 === 0),
); // => [{ a: 2 }]

product

Number

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.

Data First

P.product(data);
P.product([1, 2, 3]); // => 6
P.product([1n, 2n, 3n]); // => 6n
P.product([]); // => 1

Data Last

P.product()(data);
P.pipe([1, 2, 3], P.product()); // => 6
P.pipe([1n, 2n, 3n], R.product()); // => 6n
P.pipe([], P.product()); // => 1

prop

Object

Gets the value of the given property.

Data First

P.prop(data, key);
P.prop({ foo: 'bar' }, 'foo'); // => 'bar'

Data Last

P.prop(key)(data);
P.pipe({ foo: 'bar' }, P.prop('foo')); // => 'bar'

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. mapToObj - Builds an object from an array of items and a single mapper for key-value pairs. Refer to the docs for more details.

Data First

P.pullObject(data, keyExtractor, valueExtractor);
P.pullObject(
    [
        { name: 'john', email: 'john@bebedag.com' },
        { name: 'jane', email: 'jane@bebedag.com' },
    ],
    P.prop('name'),
    P.prop('email'),
); // => { john: "john@bebedag.com", jane: "jane@bebedag.com" }

Data Last

P.pullObject(keyExtractor, valueExtractor)(data);
P.pipe(
    [
        { name: 'john', email: 'john@bebedag.com' },
        { name: 'jane', email: 'jane@bebedag.com' },
    ],
    P.pullObject(P.prop('email'), P.prop('name')),
); // => { john: "john@bebedag.com", jane: "jane@bebedag.com" }

randomInteger

Number

Generate a random integer between from and to (inclusive).

Data First

P.randomInt(from, to);
P.randomInt(1, 10); // => 5
P.randomInt(1.5, 2.6); // => 2

randomString

String

Random a non-cryptographic random string from characters a-zA-Z0-9.

Data First

P.randomString(length);
P.randomString(5); // => aB92J

Data Last

P.randomString()(length);
P.pipe(5, P.randomString()); // => aB92J

range

Array

Returns a list of numbers from start (inclusive) to end (exclusive).

Data First

range(start, end);
P.range(1, 5); // => [1, 2, 3, 4]

Data First

range(end)(start);
P.range(5)(1); // => [1, 2, 3, 4]

rankBy

Array

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

P.rankBy(data, item, ...rules);
const DATA = [{ a: 5 }, { a: 1 }, { a: 3 }] as const;
P.rankBy(DATA, 0, P.prop('a')); // => 0
P.rankBy(DATA, 1, P.prop('a')); // => 1
P.rankBy(DATA, 2, P.prop('a')); // => 1
P.rankBy(DATA, 3, P.prop('a')); // => 2

Data Last

P.rankBy(item, ...rules)(data);
const DATA = [{ a: 5 }, { a: 1 }, { a: 3 }] as const;
P.pipe(DATA, P.rankBy(0, P.prop('a'))); // => 0
P.pipe(DATA, P.rankBy(1, P.prop('a'))); // => 1
P.pipe(DATA, P.rankBy(2, P.prop('a'))); // => 1
P.pipe(DATA, P.rankBy(3, P.prop('a'))); // => 2

reduce

Array

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

P.reduce(data, callbackfn, initialValue);
P.reduce([1, 2, 3, 4, 5], (acc, x) => acc + x, 100); // => 115

Data Last

P.reduce(fn, initialValue)(array);
P.pipe(
    [1, 2, 3, 4, 5],
    P.reduce((acc, x) => acc + x, 100),
); // => 115

reverse

Array

Reverses array.

Data First

P.reverse(arr);
P.reverse([1, 2, 3]); // [3, 2, 1]

Data Last

P.reverse()(array);
P.reverse()([1, 2, 3]); // [3, 2, 1]

round

Number

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

P.round(value, precision);
P.round(123.9876, 3); // => 123.988
P.round(483.22243, 1); // => 483.2
P.round(8541, -1); // => 8540
P.round(456789, -3); // => 457000

Data Last

P.round(precision)(value);
P.round(3)(123.9876); // => 123.988
P.round(1)(483.22243); // => 483.2
P.round(-1)(8541); // => 8540
P.round(-3)(456789); // => 457000

sample

Array

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.

Data First

P.sample(array, sampleSize);
P.sample(['hello', 'world'], 1); // => ["hello"] // typed string[]
P.sample(['hello', 'world'] as const, 1); // => ["world"] // typed ["hello" | "world"]

Data Last

P.sample(sampleSize)(array);
P.sample(1)(['hello', 'world']); // => ["hello"] // typed string[]
P.sample(1)(['hello', 'world'] as const); // => ["world"] // typed ["hello" | "world"]

set

Object

Sets the value at prop of object.

To add a new property to an object, or to override its type, use addProp instead, and to set a property within a nested object use setPath.

Data First

P.set(obj, prop, value);
P.set({ a: 1 }, 'a', 2); // => { a: 2 }

Data Last

P.set(prop, value)(obj);
P.pipe({ a: 1 }, P.set('a', 2)); // => { a: 2 }

setPath

Object

Sets the value at path of object.

For simple cases where the path is only one level deep, prefer set instead.

Data First

P.setPath(obj, path, value);
P.setPath({ a: { b: 1 } }, ['a', 'b'], 2); // => { a: { b: 2 } }

Data Last

P.setPath(path, value)(obj);
P.pipe({ a: { b: 1 } }, P.setPath(['a', 'b'], 2)); // { a: { b: 2 } }

shuffle

Array

Shuffles the input array, returning a new array with the same elements in a random order.

Data First

P.shuffle(array);
P.shuffle([4, 2, 7, 5]); // => [7, 5, 4, 2]

Data Last

P.shuffle()(array);
P.pipe([4, 2, 7, 5], P.shuffle()); // => [7, 5, 4, 2]

sleep

Function

Delay execution for a given number of milliseconds.

P.sleep(timeout);
P.sleep(1000); // => Promise<void>

sliceString

String

Extracts a section of this string and returns it as a new string, without modifying the original string. Equivalent to String.prototype.slice.

Data Last

P.sliceString(data, indexStart, indexEnd);
P.sliceString('abcdefghijkl', 1); // => `bcdefghijkl`
P.sliceString('abcdefghijkl', 4, 7); // => `efg`

Data Last

P.sliceString(indexStart, indexEnd)(string);
P.sliceString(1)('abcdefghijkl'); // => `bcdefghijkl`
P.sliceString(4, 7)('abcdefghijkl'); // => `efg`

slugify

String

Turn any string into a URL/DOM safe string.

P.slugify(str);
P.slugify('FooBar'); // => 'foobar'
P.slugify('This!-is*&%#@^up!'); // => 'this-is-up'

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

P.sort(items, cmp);
P.sort([4, 2, 7, 5], (a, b) => a - b); // => [2, 4, 5, 7]

Data Last

P.sort(cmp)(items);
P.pipe(
    [4, 2, 7, 5],
    P.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): firstBy === first(sortBy(data, ...rules)), O(n). takeFirstBy === take(sortBy(data, ...rules), k), O(nlogk). dropFirstBy === drop(sortBy(data, ...rules), k), O(nlogk). nthBy === sortBy(data, ...rules).at(k), O(n). rankBy === sortedIndex(sortBy(data, ...rules), item), O(n). Refer to the docs for more details.

Data Last

P.sortBy(...rules)(data);
P.pipe([{ a: 1 }, { a: 3 }, { a: 7 }, { a: 2 }], P.sortBy(P.prop('a'))); // => [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 7 }]

Data First

P.sortBy(data, ...rules);
P.sortBy([{ a: 1 }, { a: 3 }, { a: 7 }, { a: 2 }], prop('a')); // => [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 7 }]
P.sortBy(
    [
        { color: 'red', weight: 2 },
        { color: 'blue', weight: 3 },
        { color: 'green', weight: 1 },
        { color: 'purple', weight: 1 },
    ],
    [prop('weight'), 'asc'],
    prop('color'),
); // => [
//   {color: 'green', weight: 1},
//   {color: 'purple', weight: 1},
//   {color: 'red', weight: 2},
//   {color: 'blue', weight: 3},
// ]

sortedIndex

Array

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.

Runs in O(logN) time.

Data First

P.sortedIndex(data, item);
P.sortedIndex(['a', 'a', 'b', 'c', 'c'], 'c'); // => 3

Data Last

P.sortedIndex(item)(data);
P.pipe(['a', 'a', 'b', 'c', 'c'], P.sortedIndex('c')); // => 3

sortedIndexBy

Array

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. sortedLastIndex - like sortedIndex, but finds the last suitable index. rankBy - scans a possibly unsorted array in-order, returning the index based on a sorting criteria.

Data First

P.sortedIndexBy(data, item, valueFunction);
P.sortedIndexBy([{ age: 20 }, { age: 22 }], { age: 21 }, prop('age')); // => 1

sortedIndexWith

Array

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:

  1. It would run at O(logN) time instead of O(N) time.
  2. 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. sortedIndexBy - like sortedIndex, but assumes sorting is based on a callbackfn. sortedLastIndex - scans a sorted array with a binary search, finding the last suitable index. sortedLastIndexBy - like sortedLastIndex, but assumes sorting is based on a callbackfn.

See also: findIndex - scans a possibly unsorted array in-order (linear search). rankBy - scans a possibly unsorted array in-order, returning the index based on a sorting criteria.

Data First

P.sortedIndexWith(data, predicate);
P.sortedIndexWith(['a', 'ab', 'abc'], (item) => item.length < 2); // => 1

Data Last

P.sortedIndexWith(predicate)(data);
P.pipe(
    ['a', 'ab', 'abc'],
    P.sortedIndexWith((item) => item.length < 2),
); // => 1

sortedLastIndex

Array

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.

Runs in O(logN) time.

Data First

P.sortedLastIndex(data, item);
P.sortedLastIndex(['a', 'a', 'b', 'c', 'c'], 'c'); // => 5

Data Last

P.sortedLastIndex(item)(data);
P.pipe(['a', 'a', 'b', 'c', 'c'], sortedLastIndex('c')); // => 5

sortedLastIndexBy

Array

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. sortedIndex - like sortedLastIndex but without a callbackfn. rankBy - scans a possibly unsorted array in-order, returning the index based on a sorting criteria.

Data First

P.sortedLastIndexBy(data, item, valueFunction);
P.sortedLastIndexBy([{ age: 20 }, { age: 22 }], { age: 21 }, prop('age')); // => 1

Data Last

P.sortedLastIndexBy(item, valueFunction)(data);
P.pipe([{ age: 20 }, { age: 22 }], sortedLastIndexBy({ age: 21 }, prop('age'))); // => 1

splice

Array

Removes elements from an array and, inserts new elements in their place.

Data First

P.splice(items, start, deleteCount, replacement);
P.splice([1, 2, 3, 4, 5, 6, 7, 8], 2, 3, []); //=> [1,2,6,7,8]
P.splice([1, 2, 3, 4, 5, 6, 7, 8], 2, 3, [9, 10]); //=> [1,2,9,10,6,7,8]

Data Last

P.splice(start, deleteCount, replacement)(items);
P.pipe([1, 2, 3, 4, 5, 6, 7, 8], P.splice(2, 3, [])); // => [1,2,6,7,8]
P.pipe([1, 2, 3, 4, 5, 6, 7, 8], P.splice(2, 3, [9, 10])); // => [1,2,9,10,6,7,8]

split

String

Takes a pattern and divides this string into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array. This function mirrors the built-in String.prototype.split method.

Data First

R.split(data, separator, limit);
R.split('a,b,c', ','); //=> ["a", "b", "c"]
R.split('a,b,c', ',', 2); //=> ["a", "b"]
R.split('a1b2c3d', /\d/u); //=> ["a", "b", "c", "d"]

Data Last

R.split(separator, limit)(data);
R.pipe('a,b,c', R.split(',')); //=> ["a", "b", "c"]
R.pipe('a,b,c', R.split(',', 2)); //=> ["a", "b"]
R.pipe('a1b2c3d', R.split(/\d/u)); //=> ["a", "b", "c", "d"]

splitAt

Array

Splits a given array at a given index.

Data First

P.splitAt(array, index);
P.splitAt([1, 2, 3], 1); // => [[1], [2, 3]]
P.splitAt([1, 2, 3, 4, 5], -1); // => [[1, 2, 3, 4], [5]]

Data Last

P.splitAt(index)(array);
P.splitAt(1)([1, 2, 3]); // => [[1], [2, 3]]
P.splitAt(-1)([1, 2, 3, 4, 5]); // => [[1, 2, 3, 4], [5]]

splitWhen

Array

Splits a given array at the first index where the given predicate returns true.

Data First

P.splitWhen(array, fn);
P.splitWhen([1, 2, 3], (x) => x === 2); // => [[1], [2, 3]]

Data Last

P.splitWhen(fn)(array);
P.splitWhen((x) => x === 2)([1, 2, 3]); // => [[1], [2, 3]]

stringToPath

Utility

Converts a path string to an array of string keys (including array index access keys).

! IMPORTANT: Attempting to pass a simple string type will result in the result being inferred as never. This is intentional to help with type- safety as this function is primarily intended to help with other "object path access" functions like pathOr or setPath.

Data First

P.stringToPathArray(path);
P.stringToPathArray('a.b[0].c'); // => ['a', 'b', '0', 'c']

subtract

Number

Subtracts two numbers.

Data First

P.subtract(value, subtrahend);
P.subtract(10, 5); // => 5
P.subtract(10, -5); // => 15
P.reduce([1, 2, 3, 4], P.subtract, 20); // => 10

Data Last

P.subtract(subtrahend)(value);
P.subtract(5)(10); // => 5
P.subtract(-5)(10); // => 15
P.map([1, 2, 3, 4], P.subtract(1)); // => [0, 1, 2, 3]

sum

Number

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.

Data First

P.sum(data);
P.sum([1, 2, 3]); // => 6
P.sum([1n, 2n, 3n]); // => 6n
P.sum([]); // => 0

Data Last

P.sum()(data);
P.pipe([1, 2, 3], P.sum()); // => 6
P.pipe([1n, 2n, 3n], R.sum()); // => 6n
P.pipe([], P.sum()); // => 0

sumBy

Array

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.

Data Last

P.sumBy(fn)(array);
P.pipe(
    [{ a: 5 }, { a: 1 }, { a: 3 }],
    P.sumBy((x) => x.a),
); // 9

Data First

P.sumBy(array, fn);
P.sumBy([{ a: 5 }, { a: 1 }, { a: 3 }], (x) => x.a); // 9

swapIndices

Array

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);
swapIndices(['a', 'b', 'c'], 0, 1); // => ['b', 'a', 'c']
swapIndices(['a', 'b', 'c'], 1, -1); // => ['c', 'b', 'a']
swapIndices('abc', 0, 1); // => 'bac'

Data Last

swapIndices(index1, index2)(data);
swapIndices(0, 1)(['a', 'b', 'c']); // => ['b', 'a', 'c']
swapIndices(0, -1)('abc'); // => 'cba'

swapProps

Object

Swaps the positions of two properties in an object based on the provided keys.

Data First

swap(data, key1, key2);
swap({ a: 1, b: 2, c: 3 }, 'a', 'b'); // => {a: 2, b: 1, c: 3}

Data Last

swap(key1, key2)(data);
swap('a', 'b')({ a: 1, b: 2, c: 3 }); // => {a: 2, b: 1, c: 3}

take

Array

Returns the first n elements of array.

Data First

P.take(array, n);
P.take([1, 2, 3, 4, 3, 2, 1], 3); // => [1, 2, 3]

Data Last

P.take(n)(array);
P.pipe([1, 2, 3, 4, 3, 2, 1], P.take(n)); // => [1, 2, 3]

takeFirstBy

Array

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

P.takeFirstBy(data, n, ...rules);
P.takeFirstBy(['aa', 'aaaa', 'a', 'aaa'], 2, (x) => x.length); // => ['a', 'aa']

Data Last

P.takeFirstBy(n, ...rules)(data);
P.pipe(
    ['aa', 'aaaa', 'a', 'aaa'],
    P.takeFirstBy(2, (x) => x.length),
); // => ['a', 'aa']

takeLast

Array

Takes the last n elements from the array.

Data First

P.takeLast(array, n);
P.takeLast([1, 2, 3, 4, 5], 2); // => [4, 5]

Data Last

P.takeLast(n)(array);
P.takeLast(2)([1, 2, 3, 4, 5]); // => [4, 5]

takeLastWhile

Array

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.

Data First

P.takeLastWhile(data, predicate);
P.takeLastWhile([1, 2, 10, 3, 4, 5], (x) => x < 10); // => [3, 4, 5]

Data Last

P.takeLastWhile(predicate)(data);
P.pipe(
    [1, 2, 10, 3, 4, 5],
    P.takeLastWhile((x) => x < 10),
); // => [3, 4, 5]

takeWhile

Array

Returns elements from the array until predicate returns false.

Data First

P.takeWhile(data, predicate);
P.takeWhile([1, 2, 3, 4, 3, 2, 1], (x) => x !== 4); // => [1, 2, 3]

Data Last

P.takeWhile(predicate)(data);
P.pipe(
    [1, 2, 3, 4, 3, 2, 1],
    P.takeWhile((x) => x !== 4),
); // => [1, 2, 3]

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

P.tap(value, fn);
P.tap('foo', console.log); // => "foo"

Data Last

P.tap(fn)(value);
P.pipe(
    [-5, -1, 2, 3],
    P.filter((n) => n > 0),
    P.tap(console.log), // prints [2, 3]
    P.map((n) => n * 2),
); // => [4, 6]

times

Array

Calls an input function n times, returning an array containing the results of those function calls.

fn is passed one argument: The current value of n, which begins at 0 and is gradually incremented to n - 1.

Data First

P.times(count, fn);
P.times(5, identity()); //=> [0, 1, 2, 3, 4]

toCamelCase

String

Convert a string to camel case.

toCamelCase(str);
toCamelCase('test'); // => 'test'
toCamelCase('test string'); // => 'testSTring'
toCamelCase('test string', { delimiter: '$' }); // => 'test$string'
toCamelCase('TestV2', { separateNumbers: true }); // => 'testV_2'
toCamelCase('__typename', { prefixCharacters: '_' }); // => '__typename'
toCamelCase('type__', { suffixCharacters: '_' }); // => 'type__'
toCamelCase('version 1.2.10', { mergeAmbiguousCharacters: true }); // => 'version1210'

toCapitalCase

String

Convert a string to capital case.

toCapitalCase(str);
toCapitalCase('test'); // => 'Test'
toCapitalCase('test string'); // => 'Test String'
toCapitalCase('test string', { delimiter: '$' }); // => 'Test$String'
toCapitalCase('testV2', { separateNumbers: true }); // => 'TEST V 2'
toCapitalCase('__typename', { prefixCharacters: '_' }); // => '__Typename'
toCapitalCase('type__', { suffixCharacters: '_' }); // => 'Type__'

toConstantCase

String

Convert a string to constant case.

toConstantCase(str);
toConstantCase('test'); // => 'TEST'
toConstantCase('test string'); // => 'TEST_STRING'
toConstantCase('test string', { delimiter: '$' }); // => 'TEST$STRING'
toConstantCase('testV2', { separateNumbers: true }); // => 'TEST_V_2'
toConstantCase('__typename', { prefixCharacters: '_' }); // => '__TYPENAME'
toConstantCase('type__', { suffixCharacters: '_' }); // => 'TYPE__'

toKebabCase

String

toKebabCase(str);
toKebabCase('test'); // => 'test'
toKebabCase('test string'); // => 'test-string'
toKebabCase('test string', { delimiter: '$' }); // => 'test$string'
toKebabCase('testV2', { separateNumbers: true }); // => 'test-v-2'
toKebabCase('__typename', { prefixCharacters: '_' }); // => '__typename'
toKebabCase('type__', { suffixCharacters: '_' }); // => 'type__'

toNoCase

String

Convert a string to space separated lower case.

toNoCase(str);
toNoCase('test'); // => 'test'
toNoCase('test string'); // => 'test string'
toNoCase('test string', { delimiter: '$' }); // => 'test$string'
toNoCase('testV2', { separateNumbers: true }); // => 'test v 2'
toNoCase('__typename', { prefixCharacters: '_' }); // => '__typename'
toNoCase('type__', { suffixCharacters: '_' }); // => 'type__'

toPascalCase

String

Convert a string to pascal case.

toPascalCase(str);
toPascalCase('test'); // => 'Test'
toPascalCase('test string'); // => 'TestString'
toPascalCase('test string', { delimiter: '$' }); // => 'Test$String'
toPascalCase('testV2', { separateNumbers: true }); // => 'TestV_2'
toPascalCase('__typename', { prefixCharacters: '_' }); // => '__Typename'
toPascalCase('type__', { suffixCharacters: '_' }); // => 'Type__'
toPascalCase('version 1.2.10', { mergeAmbiguousCharacters: true }); // => 'Version1210'

toPascalSnakeCase

String

Convert a string to kebab case.

toPascalSnakeCase(str);
toPascalSnakeCase('test'); // => 'Test'
toPascalSnakeCase('test string'); // => 'Test_String'
toPascalSnakeCase('test string', { delimiter: '$' }); // => 'Test$String'
toPascalSnakeCase('testV2', { separateNumbers: true }); // => 'Test_V_2'
toPascalSnakeCase('__typename', { prefixCharacters: '_' }); // => '__Typename'
toPascalSnakeCase('type__', { suffixCharacters: '_' }); // => 'Type__'

toSentenceCase

String

toSentenceCase(str);
toSentenceCase('test'); // => 'Test'
toSentenceCase('test string'); // => 'Test string'
toSentenceCase('test string', { delimiter: '$' }); // => 'Test$String'
toSentenceCase('testV2', { separateNumbers: true }); // => 'Test v 2'
toSentenceCase('__typename', { prefixCharacters: '_' }); // => '__Typename'
toSentenceCase('type__', { suffixCharacters: '_' }); // => 'Type__'

toSnakeCase

String

toSnakeCase(str);
toSnakeCase('test'); // => 'test'
toSnakeCase('test string'); // => 'test_string'
toSnakeCase('test string', { delimiter: '$' }); // => 'test$string'
toSnakeCase('testV2', { separateNumbers: true }); // => 'test_v_2'
toSnakeCase('__typename', { prefixCharacters: '_' }); // => '__typename'
toSnakeCase('type__', { suffixCharacters: '_' }); // => 'type__'

toTrainCase

String

Convert a string to sentence case.

toTrainCase(str);
toTrainCase('test'); // => 'Test'
toTrainCase('test string'); // => 'Test-String'
toTrainCase('test string', { delimiter: '$' }); // => 'Test$String'
toTrainCase('testV2', { separateNumbers: true }); // => 'Test-V-2'
toTrainCase('__typename', { prefixCharacters: '_' }); // => '__Typename'
toTrainCase('type__', { suffixCharacters: '_' }); // => 'Type__'

unique

Array

Returns a new array containing only one copy of each element in the original list. Elements are compared by reference using Set.

Data First

P.unique(array);
P.unique([1, 2, 2, 5, 1, 6, 7]); // => [1, 2, 5, 6, 7]

Data Last

P.unique()(array);
P.pipe(
    [1, 2, 2, 5, 1, 6, 7], // only 4 iterations
    P.unique(),
    P.take(3),
); // => [1, 2, 5]

uniqueBy

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

P.uniqueBy(data, keyFunction);
P.uniqueBy(
    [{ n: 1 }, { n: 2 }, { n: 2 }, { n: 5 }, { n: 1 }, { n: 6 }, { n: 7 }],
    (obj) => obj.n,
); // => [{n: 1}, {n: 2}, {n: 5}, {n: 6}, {n: 7}]

Data Last

P.uniqueBy(keyFunction)(data);
P.pipe(
    [{ n: 1 }, { n: 2 }, { n: 2 }, { n: 5 }, { n: 1 }, { n: 6 }, { n: 7 }], // only 4 iterations
    P.uniqueBy((obj) => obj.n),
    P.take(3),
); // => [{n: 1}, {n: 2}, {n: 5}]

uniqueWith

Array

Returns a new array containing only one copy of each element in the original list. Elements are compared by custom comparator isEquals.

Data First

P.uniqueWith(array, isEquals);
P.uniqueWith(
    [{ a: 1 }, { a: 2 }, { a: 2 }, { a: 5 }, { a: 1 }, { a: 6 }, { a: 7 }],
    P.equals,
); // => [{a: 1}, {a: 2}, {a: 5}, {a: 6}, {a: 7}]

Data Last

P.uniqueWith(isEquals)(array);
P.uniqueWith(P.equals)([
    { a: 1 },
    { a: 2 },
    { a: 2 },
    { a: 5 },
    { a: 1 },
    { a: 6 },
    { a: 7 },
]); // => [{a: 1}, {a: 2}, {a: 5}, {a: 6}, {a: 7}]
P.pipe(
    [{ a: 1 }, { a: 2 }, { a: 2 }, { a: 5 }, { a: 1 }, { a: 6 }, { a: 7 }], // only 4 iterations
    P.uniqueWith(P.equals),
    P.take(3),
); // => [{a: 1}, {a: 2}, {a: 5}]

values

Object

Returns a new array containing the values of the array or object.

Data First

P.values(source);
P.values(['x', 'y', 'z']); // => ['x', 'y', 'z']
P.values({ a: 'x', b: 'y', c: 'z' }); // => ['x', 'y', 'z']

Data Last

P.values()(source);
P.pipe(['x', 'y', 'z'], P.values()); // => ['x', 'y', 'z']
P.pipe({ a: 'x', b: 'y', c: 'z' }, P.values()); // => ['x', 'y', 'z']
P.pipe({ a: 'x', b: 'y', c: 'z' }, P.values(), P.first()); // => 'x'

zip

Array

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.

Data First

P.zip(first, second);
P.zip([1, 2], ['a', 'b']); // => [[1, 'a'], [2, 'b']]

Data Last

P.zip(second)(first);
P.zip(['a', 'b'])([1, 2]); // => [[1, 'a'], [2, 'b']]

zipWith

Array

Creates a new list from two supplied lists by calling the supplied function with the same-positioned element from each list.

P.zipWith(fn)(first, second);
P.zipWith((a: string, b: string) => a + b)(['1', '2', '3'], ['a', 'b', 'c']); // => ['1a', '2b', '3c']

Data Last

P.zipWith(second, fn)(first);
P.pipe(
    ['1', '2', '3'],
    P.zipWith(['a', 'b', 'c'], (a, b) => a + b),
); // => ['1a', '2b', '3c']

Data First

P.zipWith(first, second, fn);
P.zipWith(['1', '2', '3'], ['a', 'b', 'c'], (a, b) => a + b); // => ['1a', '2b', '3c']