Skip to content

Files

Latest commit

 

History

History

docs

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

Rambdax

Extended version of Rambda(utility library) - Documentation

Rambda is smaller and faster alternative to the popular functional programming library Ramda. - Documentation

install size GitHub contributors codecov Library size

❯ Differences between Rambda and Rambdax

Rambdax passthrough all Rambda methods and introduce some new functions.

The idea of Rambdax is to extend Rambda without worring for Ramda compatibility.

---------------

❯ Example use

import { composeAsync, filter, delay, mapAsync } from 'rambdax'

const result = await composeAsync(
  mapAsync(async x => {
    await delay(100)
    return x + 1
  }),
  filter(x => x > 1)
)([1, 2, 3])
// => [3, 4]

You can test this example in Rambda's REPL

---------------

❯ Rambdax's advantages

TypeScript included

TypeScript definitions are included in the library, in comparison to Ramda, where you need to additionally install @types/ramda.

Still, you need to be aware that functional programming features in TypeScript are in development, which means that using R.compose/R.pipe can be problematic.

Important - Rambdax version 9.0.0(or higher) requires TypeScript version 4.3.3(or higher).

Dot notation for R.path, R.paths, R.assocPath and R.lensPath

Standard usage of R.path is R.path(['a', 'b'], {a: {b: 1} }).

In Rambda you have the choice to use dot notation(which is arguably more readable):

R.path('a.b', {a: {b: 1} })

Comma notation for R.pick and R.omit

Similar to dot notation, but the separator is comma(,) instead of dot(.).

R.pick('a,b', {a: 1 , b: 2, c: 3} })
// No space allowed between properties

Extendable with Ramda community projects

Rambdax implements some methods from Ramda community projects, such as R.lensSatisfies, R.lensEq and R.viewOr.

Understandable source code due to little usage of internals

Ramda uses a lot of internals, which hides a lot of logic. Reading the full source code of a method can be challenging.

Better VSCode experience

If the project is written in Javascript, then go to source definition action will lead you to actual implementation of the method.

Deno support

import * as R from "https://deno.land/x/rambdax/mod.ts";

Alternative TS definitions

Alternative TS definitions are available as rambdax/immutable. These are Rambdax definitions linted with ESLint functional/prefer-readonly-type plugin.

---------------

❯ Missing Ramda methods

Click to see the full list of 46 Ramda methods not implemented in Rambda and their status.
  • construct - Using classes is not very functional programming oriented.
  • constructN - same as above
  • into - no support for transducer as it is overly complex to implement, understand and read.
  • invert - overly complicated and limited use case
  • invertObj
  • invoker
  • keysIn - we shouldn't encourage extending object with .prototype
  • lift
  • liftN
  • mapAccum - Ramda example doesn't looks convincing
  • mapAccumRight
  • memoizeWith - hard to imagine its usage in context of R.pipe/R.compose
  • mergeDeepWith - limited use case
  • mergeDeepWithKey
  • mergeWithKey
  • nAry - hard to argument about and hard to create meaningful TypeScript definitions
  • nthArg - limited use case
  • o - enough TypeScript issues with R.pipe/R.compose to add more composition methods
  • otherwise - naming is confusing
  • pair - left-pad types of debacles happens partially because of such methods that should not be hidden, bur rather part of your code base even if they need to exist.
  • partialRight - I dislike R.partial, so I don't want to add more methods that are based on it
  • pipeWith
  • project - naming is confusing, but also limited use case
  • promap
  • reduceRight - I find right/left methods confusing so I added them only where it makes sense.
  • reduceWhile - functions with 4 inputs - I think that even 3 is too much
  • reduced
  • remove - nice name but it is too generic. Also, Rambdax has such method and there it works very differently
  • scan - hard to explain
  • sequence
  • splitWhenever
  • symmetricDifferenceWith
  • andThen
  • toPairsIn
  • transduce - currently is out of focus
  • traverse - same as above
  • unary
  • uncurryN
  • unfold - similar to R.scan and I find that it doesn't help with readability
  • unionWith - why it has its usage, I want to limit number of methods that accept more than 2 arguments
  • until
  • useWith - hard to explain
  • valuesIn
  • xprod - limited use case
  • thunkify
  • __ - placeholder method allows user to further customize the method call. While, it seems useful initially, the price is too high in terms of complexity for TypeScript definitions. If it is not easy exressable in TypeScript, it is not worth it as Rambda is a TypeScript first library.

The following methods are not going to be added(reason for exclusion is provided as a comment):

---------------

❯ Install

  • yarn add rambdax

  • For UMD usage either use ./dist/rambdax.umd.js or the following CDN link:

https://unpkg.com/rambdax@CURRENT_VERSION/dist/rambdax.umd.js
  • with deno
import {add} from "https://deno.land/x/rambda/mod.ts";

---------------

Differences between Rambda and Ramda

  • Rambda's type detects async functions and unresolved Promises. The returned values are 'Async' and 'Promise'.

  • Rambda's type handles NaN input, in which case it returns NaN.

  • Rambda's forEach can iterate over objects not only arrays.

  • Rambda's map, filter, partition when they iterate over objects, they pass property and input object as predicate's argument.

  • Rambda's filter returns empty array with bad input(null or undefined), while Ramda throws.

  • Ramda's clamp work with strings, while Rambda's method work only with numbers.

  • Ramda's indexOf/lastIndexOf work with strings and lists, while Rambda's method work only with lists as iterable input.

  • Error handling, when wrong inputs are provided, may not be the same. This difference will be better documented once all brute force tests are completed.

  • TypeScript definitions between rambda and @types/ramda may vary.

---------------

❯ Benchmarks

Click to expand all benchmark results

There are methods which are benchmarked only with Ramda and Rambda(i.e. no Lodash).

Note that some of these methods, are called with and without curring. This is done in order to give more detailed performance feedback.

The benchmarks results are produced from latest versions of Rambda, Lodash(4.17.21) and Ramda(0.30.1).

method Rambda Ramda Lodash
add 🚀 Fastest 21.52% slower 82.15% slower
adjust 8.48% slower 🚀 Fastest 🔳
all 🚀 Fastest 7.18% slower 🔳
allPass 🚀 Fastest 88.25% slower 🔳
allPass 🚀 Fastest 98.56% slower 🔳
and 🚀 Fastest 89.09% slower 🔳
any 🚀 Fastest 92.87% slower 45.82% slower
anyPass 🚀 Fastest 98.25% slower 🔳
append 🚀 Fastest 2.07% slower 🔳
applySpec 🚀 Fastest 80.43% slower 🔳
assoc 72.32% slower 60.08% slower 🚀 Fastest
clone 🚀 Fastest 91.86% slower 86.48% slower
compose 6.07% slower 16.89% slower 🚀 Fastest
converge 78.63% slower 🚀 Fastest 🔳
curry 🚀 Fastest 28.86% slower 🔳
curryN 🚀 Fastest 41.05% slower 🔳
defaultTo 🚀 Fastest 48.91% slower 🔳
drop 🚀 Fastest 82.35% slower 🔳
dropLast 🚀 Fastest 86.74% slower 🔳
equals 58.37% slower 96.73% slower 🚀 Fastest
filter 6.7% slower 72.03% slower 🚀 Fastest
find 🚀 Fastest 85.14% slower 42.65% slower
findIndex 🚀 Fastest 86.48% slower 72.27% slower
flatten 🚀 Fastest 85.68% slower 3.57% slower
ifElse 🚀 Fastest 58.56% slower 🔳
includes 🚀 Fastest 81.64% slower 🔳
indexOf 🚀 Fastest 80.17% slower 🔳
indexOf 🚀 Fastest 82.2% slower 🔳
init 🚀 Fastest 92.24% slower 13.3% slower
is 🚀 Fastest 57.69% slower 🔳
isEmpty 🚀 Fastest 97.14% slower 54.99% slower
last 🚀 Fastest 93.43% slower 5.28% slower
lastIndexOf 🚀 Fastest 85.19% slower 🔳
map 🚀 Fastest 86.6% slower 11.73% slower
match 🚀 Fastest 44.83% slower 🔳
merge 🚀 Fastest 12.21% slower 55.76% slower
none 🚀 Fastest 96.48% slower 🔳
objOf 🚀 Fastest 38.05% slower 🔳
omit 🚀 Fastest 69.95% slower 97.34% slower
over 🚀 Fastest 56.23% slower 🔳
path 37.81% slower 77.81% slower 🚀 Fastest
pick 🚀 Fastest 19.07% slower 80.2% slower
pipe 🚀 Fastest 0.11% slower 🔳
prop 🚀 Fastest 87.95% slower 🔳
propEq 🚀 Fastest 91.92% slower 🔳
range 🚀 Fastest 61.8% slower 57.44% slower
reduce 60.48% slower 77.1% slower 🚀 Fastest
repeat 48.57% slower 68.98% slower 🚀 Fastest
replace 33.45% slower 33.99% slower 🚀 Fastest
set 🚀 Fastest 50.35% slower 🔳
sort 🚀 Fastest 40.23% slower 🔳
sortBy 🚀 Fastest 25.29% slower 56.88% slower
split 🚀 Fastest 55.37% slower 17.64% slower
splitEvery 🚀 Fastest 71.98% slower 🔳
take 🚀 Fastest 91.96% slower 4.72% slower
takeLast 🚀 Fastest 93.39% slower 19.22% slower
test 🚀 Fastest 82.34% slower 🔳
type 🚀 Fastest 48.6% slower 🔳
uniq 🚀 Fastest 84.9% slower 🔳
uniqBy 51.93% slower 🚀 Fastest 🔳
uniqWith 8.29% slower 🚀 Fastest 🔳
uniqWith 14.23% slower 🚀 Fastest 🔳
update 🚀 Fastest 52.35% slower 🔳
view 🚀 Fastest 76.15% slower 🔳

---------------

❯ Used by

---------------

API

add

add(a: number, b: number): number

It adds a and b.

💥 It doesn't work with strings, as the inputs are parsed to numbers before calculation.

R.add(2, 3) // =>  5

Try this R.add example in Rambda REPL

All TypeScript definitions
add(a: number, b: number): number;
add(a: number): (b: number) => number;
R.add source
export function add(a, b){
  if (arguments.length === 1) return _b => add(a, _b)

  return Number(a) + Number(b)
}
Tests
import { add as addRamda } from 'ramda'

import { compareCombinations } from './_internals/testUtils.js'
import { add } from './add.js'

test('with number', () => {
  expect(add(2, 3)).toBe(5)
  expect(add(7)(10)).toBe(17)
})

test('string is bad input', () => {
  expect(add('foo', 'bar')).toBeNaN()
})

test('ramda specs', () => {
  expect(add('1', '2')).toBe(3)
  expect(add(1, '2')).toBe(3)
  expect(add(true, false)).toBe(1)
  expect(add(null, null)).toBe(0)
  expect(add(undefined, undefined)).toBeNaN()
  expect(add(new Date(1), new Date(2))).toBe(3)
})

const possibleInputs = [
  /foo/,
  'foo',
  true,
  3,
  NaN,
  4,
  [],
  Promise.resolve(1),
]

describe('brute force', () => {
  compareCombinations({
    fn          : add,
    fnRamda     : addRamda,
    firstInput  : possibleInputs,
    secondInput : possibleInputs,
    callback    : errorsCounters => {
      expect(errorsCounters).toMatchInlineSnapshot(`
        {
          "ERRORS_MESSAGE_MISMATCH": 0,
          "ERRORS_TYPE_MISMATCH": 0,
          "RESULTS_MISMATCH": 0,
          "SHOULD_NOT_THROW": 0,
          "SHOULD_THROW": 0,
          "TOTAL_TESTS": 64,
        }
      `)
    },
  })
})

---------------

addIndex

addIndex(originalFn: any): (fn: any) => (list: any[]) => any[]
const result = R.addIndex(R.map)((val, idx) => val + idx + 1, [1, 2, 3])
// => [2, 4, 6]

Try this R.addIndex example in Rambda REPL

All TypeScript definitions
addIndex(originalFn: any): (fn: any) => (list: any[]) => any[];
addIndex(originalFn: any): (fn: any, list: any[]) => any[];
R.addIndex source
import { _concat } from './_internals/utils.js'
import { curryN } from './curryN.js'

export function addIndex(
  originalFunction,
  initialIndexFn = () => 0,
  loopIndexChange = x => x + 1
){
  return curryN(originalFunction.length, function (){
    const origFn = arguments[ 0 ]
    const list = arguments[ arguments.length - 1 ]
    let idx = initialIndexFn(list.length)
    const args = Array.prototype.slice.call(arguments, 0)
    args[ 0 ] = function (){
      const result = origFn.apply(this, _concat(arguments, [ idx, list ]))
      idx = loopIndexChange(idx)

      return result
    }

    return originalFunction.apply(this, args)
  })
}
Tests
import * as R from 'ramda'

import { addIndex } from './addIndex.js'
import { map } from './map.js'

test('with R.pipe', () => {
  const result = R.pipe(R.addIndex(R.map)((x, i) => x + i))([ 1, 2, 3 ])
  expect(result).toEqual([ 1, 3, 5 ])
})

test('happy', () => {
  function mapFn(fn, list){
    const willReturn = []
    list.forEach(item => {
      willReturn.push(fn(item))
    })

    return willReturn
  }
  const mapIndexed = addIndex(mapFn)
  const fn2 = (val, idx) => val + idx + 5
  const result = mapIndexed(fn2, [ 1, 2, 3 ])
  expect(result).toEqual([ 6, 8, 10 ])
})

describe('unary functions like `map`', () => {
  const times2 = function (x){
    return x * 2
  }
  const addIndexParam = function (x, idx){
    return x + idx
  }
  const squareEnds = function (
    x, idx, list
  ){
    return idx === 0 || idx === list.length - 1 ? x * x : x
  }
  const mapIndexed = addIndex(map)

  it('works just like a normal map', () => {
    expect(mapIndexed(times2, [ 1, 2, 3, 4 ])).toEqual([ 2, 4, 6, 8 ])
  })

  it('passes the index as a second parameter to the callback', () => {
    expect(mapIndexed(addIndexParam, [ 8, 6, 7, 5, 3, 0, 9 ])).toEqual([
      8, 7, 9, 8, 7, 5, 15,
    ])
  })

  it('passes the entire list as a third parameter to the callback', () => {
    expect(mapIndexed(squareEnds, [ 8, 6, 7, 5, 3, 0, 9 ])).toEqual([
      64, 6, 7, 5, 3, 0, 81,
    ])
  })

  it('acts as a curried function', () => {
    const makeSquareEnds = mapIndexed(squareEnds)
    expect(makeSquareEnds([ 8, 6, 7, 5, 3, 0, 9 ])).toEqual([
      64, 6, 7, 5, 3, 0, 81,
    ])
  })
})

---------------

addIndexRight

addIndexRight(originalFn: any): (fn: any) => (list: any[]) => any[]

Same as R.addIndex, but it will passed indexes are decreasing, instead of increasing.

All TypeScript definitions
addIndexRight(originalFn: any): (fn: any) => (list: any[]) => any[];
addIndexRight(originalFn: any): (fn: any, list: any[]) => any[];
R.addIndexRight source
import { addIndex } from './addIndex.js'

export function addIndexRight(originalFunction){
  return addIndex(
    originalFunction,
    listLength => listLength - 1,
    x => x - 1
  )
}
Tests
import { addIndexRight } from './addIndexRight.js'
import { map } from './map.js'

test('happy', () => {
  function mapFn(fn, list){
    const willReturn = []
    list.forEach(item => {
      willReturn.push(fn(item))
    })

    return willReturn
  }
  const mapIndexed = addIndexRight(mapFn)
  const fn2 = (val, idx) => val + idx + 5
  expect(mapIndexed(fn2, [ 1, 2, 3 ])).toEqual([ 8, 8, 8 ])
  const revmap = (fn, ary) => map(fn, ary)
  const revmapIndexed = addIndexRight(revmap)
  const result = revmapIndexed((val, idx) => idx + '-' + val,
    [ 'f', 'o', 'o', 'b', 'a', 'r' ])

  expect(result).toEqual([ '5-f', '4-o', '3-o', '2-b', '1-a', '0-r' ])
})

---------------

adjust

adjust<T>(index: number, replaceFn: (x: T) => T, list: T[]): T[]

It replaces index in array list with the result of replaceFn(list[i]).

const result = R.adjust(
  0,
  a => a + 1,
  [0, 100]
) // => [1, 100]

Try this R.adjust example in Rambda REPL

All TypeScript definitions
adjust<T>(index: number, replaceFn: (x: T) => T, list: T[]): T[];
adjust<T>(index: number, replaceFn: (x: T) => T): (list: T[]) => T[];
R.adjust source
import { cloneList } from './_internals/cloneList.js'
import { curry } from './curry.js'

function adjustFn(
  index, replaceFn, list
){
  const actualIndex = index < 0 ? list.length + index : index
  if (index >= list.length || actualIndex < 0) return list

  const clone = cloneList(list)
  clone[ actualIndex ] = replaceFn(clone[ actualIndex ])

  return clone
}

export const adjust = curry(adjustFn)
Tests
import { add } from './add.js'
import { adjust } from './adjust.js'
import { pipe } from './pipe.js'

const list = [ 0, 1, 2 ]
const expected = [ 0, 11, 2 ]

test('happy', () => {})

test('happy', () => {
  expect(adjust(
    1, add(10), list
  )).toEqual(expected)
})

test('with curring type 1 1 1', () => {
  expect(adjust(1)(add(10))(list)).toEqual(expected)
})

test('with curring type 1 2', () => {
  expect(adjust(1)(add(10), list)).toEqual(expected)
})

test('with curring type 2 1', () => {
  expect(adjust(1, add(10))(list)).toEqual(expected)
})

test('with negative index', () => {
  expect(adjust(
    -2, add(10), list
  )).toEqual(expected)
})

test('when index is out of bounds', () => {
  const list = [ 0, 1, 2, 3 ]
  expect(adjust(
    4, add(1), list
  )).toEqual(list)
  expect(adjust(
    -5, add(1), list
  )).toEqual(list)
})

---------------

all

all<T>(predicate: (x: T) => boolean, list: T[]): boolean

It returns true, if all members of array list returns true, when applied as argument to predicate function.

const list = [ 0, 1, 2, 3, 4 ]
const predicate = x => x > -1

const result = R.all(predicate, list)
// => true

Try this R.all example in Rambda REPL

All TypeScript definitions
all<T>(predicate: (x: T) => boolean, list: T[]): boolean;
all<T>(predicate: (x: T) => boolean): (list: T[]) => boolean;
R.all source
export function all(predicate, list){
  if (arguments.length === 1) return _list => all(predicate, _list)

  for (let i = 0; i < list.length; i++){
    if (!predicate(list[ i ])) return false
  }

  return true
}
Tests
import { all } from './all.js'

const list = [ 0, 1, 2, 3, 4 ]

test('when true', () => {
  const fn = x => x > -1

  expect(all(fn)(list)).toBeTrue()
})

test('when false', () => {
  const fn = x => x > 2

  expect(all(fn, list)).toBeFalse()
})

---------------

allFalse

allFalse(...inputs: any[]): boolean

It returns true if all inputs arguments are falsy(empty objects and empty arrays are considered falsy).

Functions are valid inputs, but these functions cannot have their own arguments.

This method is very similar to R.anyFalse, R.anyTrue and R.allTrue

R.allFalse(0, null, [], {}, '', () => false)
// => true

Try this R.allFalse example in Rambda REPL

All TypeScript definitions
allFalse(...inputs: any[]): boolean;
R.allFalse source
import { isTruthy } from './_internals/isTruthy.js'
import { type } from './type.js'

export function allFalse(...inputs){
  let counter = 0
  while (counter < inputs.length){
    const x = inputs[ counter ]

    if (type(x) === 'Function'){
      if (isTruthy(x())){
        return false
      }
    } else if (isTruthy(x)){
      return false
    }

    counter++
  }

  return true
}
Tests
import { runTests } from 'helpers-fn'

import { allFalse } from './allFalse.js'

const happy = { ok : [ () => false, () => [], () => {}, null, false, [] ] }
const withArray = { fail : [ ...happy.ok, [ 1 ] ] }
const withObject = { fail : [ ...happy.ok, { a : 1 } ] }
const withFunction = { fail : [ ...happy.ok, () => ({ a : 1 }) ] }
const withBoolean = { fail : [ ...happy.ok, true ] }

const testData = {
  label : 'R.allFalse',
  data  : [ happy, withArray, withObject, withFunction, withBoolean ],
  fn    : input => allFalse(...input),
}
runTests(testData)

---------------

allPass

allPass<T>(predicates: ((x: T) => boolean)[]): (input: T) => boolean

It returns true, if all functions of predicates return true, when input is their argument.

const input = {
  a : 1,
  b : 2,
}
const predicates = [
  x => x.a === 1,
  x => x.b === 2,
]
const result = R.allPass(predicates)(input) // => true

Try this R.allPass example in Rambda REPL

All TypeScript definitions
allPass<T>(predicates: ((x: T) => boolean)[]): (input: T) => boolean;
allPass<T>(predicates: ((...inputs: T[]) => boolean)[]): (...inputs: T[]) => boolean;
R.allPass source
export function allPass(predicates){
  return (...input) => {
    let counter = 0
    while (counter < predicates.length){
      if (!predicates[ counter ](...input)){
        return false
      }
      counter++
    }

    return true
  }
}
Tests
import { allPass } from './allPass.js'

test('happy', () => {
  const rules = [ x => typeof x === 'number', x => x > 10, x => x * 7 < 100 ]

  expect(allPass(rules)(11)).toBeTrue()

  expect(allPass(rules)(undefined)).toBeFalse()
})

test('when returns true', () => {
  const conditionArr = [ val => val.a === 1, val => val.b === 2 ]

  expect(allPass(conditionArr)({
    a : 1,
    b : 2,
  })).toBeTrue()
})

test('when returns false', () => {
  const conditionArr = [ val => val.a === 1, val => val.b === 3 ]

  expect(allPass(conditionArr)({
    a : 1,
    b : 2,
  })).toBeFalse()
})

test('works with multiple inputs', () => {
  const fn = function (
    w, x, y, z
  ){
    return w + x === y + z
  }
  expect(allPass([ fn ])(
    3, 3, 3, 3
  )).toBeTrue()
})

---------------

allTrue

allTrue(...input: any[]): boolean

It returns true if all inputs arguments are truthy(empty objects and empty arrays are considered falsy).

R.allTrue(1, true, {a: 1}, [1], 'foo', () => true)
// => true

Try this R.allTrue example in Rambda REPL

All TypeScript definitions
allTrue(...input: any[]): boolean;
R.allTrue source
import { isFalsy } from './_internals/isFalsy.js'
import { type } from './type.js'

export function allTrue(...inputs){
  let counter = 0
  while (counter < inputs.length){
    const x = inputs[ counter ]

    if (type(x) === 'Function'){
      if (isFalsy(x())){
        return false
      }
    } else if (isFalsy(x)){
      return false
    }

    counter++
  }

  return true
}
Tests
import { allTrue } from './allTrue.js'

test('with functions', () => {
  const foo = () => 1
  const bar = () => false
  const baz = () => JSON.parse('{sda')
  const result = allTrue(
    foo, bar, baz
  )
  expect(result).toBeFalse()
})

test('usage with non boolean', () => {
  const foo = { a : 1 }
  const baz = [ 1, 2, 3 ]

  const result = allTrue(
    foo, foo, baz
  )
  expect(result).toBeTrue()
})

test('usage with boolean', () => {
  const foo = 4
  const baz = [ 1, 2, 3 ]

  const result = allTrue(foo > 2, baz.length === 3)
  expect(result).toBeTrue()
})

test('escapes early - case 0', () => {
  const foo = undefined
  const result = allTrue(foo, () => foo.a)
  expect(result).toBeFalse()
})

test('escapes early - case 1', () => {
  const foo = null
  const result = allTrue(foo, () => foo.a)
  expect(result).toBeFalse()
})

test('escapes early - case 2', () => {
  const foo = { a : 'bar' }
  const result = allTrue(
    foo, foo.a, foo.a.b
  )
  expect(result).toBeFalse()
})

test('escapes early - case 3', () => {
  const foo = { a : { b : 'foo' } }
  const result = allTrue(
    foo,
    () => foo.a,
    () => foo.a.b
  )
  expect(result).toBeTrue()
})

---------------

allType

allType(targetType: RambdaTypes): (...input: any[]) => boolean

It returns a function which will return true if all of its inputs arguments belong to targetType.

💥 targetType is one of the possible returns of R.type

const targetType = 'String'

const result = R.allType(
  targetType
)('foo', 'bar', 'baz')
// => true

Try this R.allType example in Rambda REPL

All TypeScript definitions
allType(targetType: RambdaTypes): (...input: any[]) => boolean;
R.allType source
import { type } from './type.js'

export function allType(targetType){
  return (...inputs) => {
    let counter = 0

    while (counter < inputs.length){
      if (type(inputs[ counter ]) !== targetType){
        return false
      }
      counter++
    }

    return true
  }
}
Tests
import { allType } from './allType.js'

test('when true', () => {
  const result = allType('Array')(
    [ 1, 2, 3 ], [], [ null ]
  )

  expect(result).toBeTrue()
})

test('when false', () => {
  const result = allType('String')(
    1, undefined, null, []
  )

  expect(result).toBeFalse()
})

---------------

always

always<T>(x: T): (...args: unknown[]) => T

It returns function that always returns x.

const fn = R.always(7)

const result = fn()
// => 7

Try this R.always example in Rambda REPL

All TypeScript definitions
always<T>(x: T): (...args: unknown[]) => T;
R.always source
export function always(x){
  return _ => x
}
Tests
import { always } from './always.js'
import { applySpec } from './applySpec.js'

test('happy', () => {
  const fn = always(7)

  expect(fn()).toBe(7)
  expect(fn()).toBe(7)
})

test('compatibility with applySpec', () => {
  const spec = applySpec({ x : always('foo') })
  expect(spec({})).toEqual({ x : 'foo' })
})

---------------

and

and<T, U>(x: T, y: U): T | U

Logical AND

R.and(true, true); // => true
R.and(false, true); // => false
R.and(true, 'foo'); // => 'foo'

Try this R.and example in Rambda REPL

All TypeScript definitions
and<T, U>(x: T, y: U): T | U;
and<T>(x: T): <U>(y: U) => T | U;
R.and source
export function and(a, b){
  if (arguments.length === 1) return _b => and(a, _b)

  return a && b
}
Tests
import { and } from './and.js'

test('happy', () => {
  expect(and(1, 'foo')).toBe('foo')
  expect(and(true, true)).toBeTrue()
  expect(and(true)(true)).toBeTrue()
  expect(and(true, false)).toBeFalse()
  expect(and(false, true)).toBeFalse()
  expect(and(false, false)).toBeFalse()
})

---------------

any

any<T>(predicate: (x: T) => boolean, list: T[]): boolean

It returns true, if at least one member of list returns true, when passed to a predicate function.

const list = [1, 2, 3]
const predicate = x => x * x > 8
R.any(fn, list)
// => true

Try this R.any example in Rambda REPL

All TypeScript definitions
any<T>(predicate: (x: T) => boolean, list: T[]): boolean;
any<T>(predicate: (x: T) => boolean): (list: T[]) => boolean;
R.any source
export function any(predicate, list){
  if (arguments.length === 1) return _list => any(predicate, _list)

  let counter = 0
  while (counter < list.length){
    if (predicate(list[ counter ], counter)){
      return true
    }
    counter++
  }

  return false
}
Tests
import { any } from './any.js'

const list = [ 1, 2, 3 ]

test('happy', () => {
  expect(any(x => x < 0, list)).toBeFalse()
})

test('with curry', () => {
  expect(any(x => x > 2)(list)).toBeTrue()
})

---------------

anyFalse

anyFalse(...input: any[]): boolean

It returns true if any of inputs is falsy(empty objects and empty arrays are considered falsy).

R.anyFalse(1, {a: 1}, [1], () => false)
// => true

Try this R.anyFalse example in Rambda REPL

All TypeScript definitions
anyFalse(...input: any[]): boolean;
R.anyFalse source
import { isFalsy } from './_internals/isFalsy.js'
import { type } from './type.js'

export function anyFalse(...inputs){
  let counter = 0
  while (counter < inputs.length){
    const x = inputs[ counter ]

    if (type(x) === 'Function'){
      if (isFalsy(x())){
        return true
      }
    } else if (isFalsy(x)){
      return true
    }

    counter++
  }

  return false
}
Tests
import { anyFalse } from './anyFalse.js'

test('when true', () => {
  expect(anyFalse(
    true, true, false
  )).toBeTruthy()
})

test('when false', () => {
  expect(anyFalse(true, true)).toBeFalsy()
})

test('supports function', () => {
  expect(anyFalse(
    true,
    () => true,
    () => false
  )).toBeTruthy()
})

---------------

anyPass

anyPass<T>(predicates: ((x: T) => boolean)[]): (input: T) => boolean

It accepts list of predicates and returns a function. This function with its input will return true, if any of predicates returns true for this input.

const isBig = x => x > 20
const isOdd = x => x % 2 === 1
const input = 11

const fn = R.anyPass(
  [isBig, isOdd]
)

const result = fn(input) 
// => true

Try this R.anyPass example in Rambda REPL

All TypeScript definitions
anyPass<T>(predicates: ((x: T) => boolean)[]): (input: T) => boolean;
anyPass<T>(predicates: ((...inputs: T[]) => boolean)[]): (...inputs: T[]) => boolean;
R.anyPass source
export function anyPass(predicates){
  return (...input) => {
    let counter = 0
    while (counter < predicates.length){
      if (predicates[ counter ](...input)){
        return true
      }
      counter++
    }

    return false
  }
}
Tests
import { anyPass } from './anyPass.js'

test('happy', () => {
  const rules = [ x => typeof x === 'string', x => x > 10 ]
  const predicate = anyPass(rules)
  expect(predicate('foo')).toBeTrue()
  expect(predicate(6)).toBeFalse()
})

test('happy', () => {
  const rules = [ x => typeof x === 'string', x => x > 10 ]

  expect(anyPass(rules)(11)).toBeTrue()
  expect(anyPass(rules)(undefined)).toBeFalse()
})

const obj = {
  a : 1,
  b : 2,
}

test('when returns true', () => {
  const conditionArr = [ val => val.a === 1, val => val.a === 2 ]

  expect(anyPass(conditionArr)(obj)).toBeTrue()
})

test('when returns false + curry', () => {
  const conditionArr = [ val => val.a === 2, val => val.b === 3 ]

  expect(anyPass(conditionArr)(obj)).toBeFalse()
})

test('with empty predicates list', () => {
  expect(anyPass([])(3)).toBeFalse()
})

test('works with multiple inputs', () => {
  const fn = function (
    w, x, y, z
  ){
    console.log(
      w, x, y, z
    )

    return w + x === y + z
  }
  expect(anyPass([ fn ])(
    3, 3, 3, 3
  )).toBeTrue()
})

---------------

anyTrue

anyTrue(...input: any[]): boolean

It returns true if any of inputs arguments are truthy(empty objects and empty arrays are considered falsy).

R.anyTrue(0, null, [], {}, '', () => true)
// => true

Try this R.anyTrue example in Rambda REPL

All TypeScript definitions
anyTrue(...input: any[]): boolean;
R.anyTrue source
import { isTruthy } from './_internals/isTruthy.js'
import { type } from './type.js'

export function anyTrue(...inputs){
  let counter = 0
  while (counter < inputs.length){
    const x = inputs[ counter ]

    if (type(x) === 'Function'){
      if (isTruthy(x())){
        return true
      }
    } else if (isTruthy(x)){
      return true
    }

    counter++
  }

  return false
}
Tests
import { anyTrue } from './anyTrue.js'

test('when true', () => {
  expect(anyTrue(
    true, true, false
  )).toBeTruthy()
})

test('when false', () => {
  expect(anyTrue(
    false, false, false
  )).toBeFalsy()
})

test('supports function', () => {
  expect(anyTrue(
    false,
    false,
    false,
    () => false,
    () => true
  )).toBeTruthy()
})

---------------

anyType

anyType(targetType: RambdaTypes): (...input: any[]) => boolean

It returns a function which will return true if at least one of its inputs arguments belongs to targetType.

targetType is one of the possible returns of R.type

💥 targetType is one of the possible returns of R.type

const targetType = 'String'

const result = R.anyType(
  targetType
)(1, {}, 'foo')
// => true

Try this R.anyType example in Rambda REPL

All TypeScript definitions
anyType(targetType: RambdaTypes): (...input: any[]) => boolean;
R.anyType source
import { type } from './type.js'

export function anyType(targetType){
  return (...inputs) => {
    let counter = 0

    while (counter < inputs.length){
      if (type(inputs[ counter ]) === targetType){
        return true
      }
      counter++
    }

    return false
  }
}
Tests
import { anyType } from './anyType.js'

test('when true', () => {
  const result = anyType('Array')(
    1, undefined, null, []
  )

  expect(result).toBeTrue()
})

test('when false', () => {
  const result = anyType('String')(
    1, undefined, null, []
  )

  expect(result).toBeFalse()
})

---------------

ap

ap<T, U>(fns: Array<(a: T) => U>[], vs: T[]): U[]

It takes a list of functions and a list of values. Then it returns a list of values obtained by applying each function to each value.

const result = R.ap(
  [
    x => x + 1,
    x => x + 2,
  ],
  [1, 2, 3]
)
// => [2, 3, 4, 3, 4, 5]

Try this R.ap example in Rambda REPL

All TypeScript definitions
ap<T, U>(fns: Array<(a: T) => U>[], vs: T[]): U[];
ap<T, U>(fns: Array<(a: T) => U>): (vs: T[]) => U[];
ap<R, A, B>(fn: (r: R, a: A) => B, fn1: (r: R) => A): (r: R) => B;
R.ap source
export function ap(functions, input){
  if (arguments.length === 1){
    return _inputs => ap(functions, _inputs)
  }

  return functions.reduce((acc, fn) => [ ...acc, ...input.map(fn) ], [])
}
Tests
import { ap } from './ap.js'

function mult2(x){
  return x * 2
}
function plus3(x){
  return x + 3
}

test('happy', () => {
  expect(ap([ mult2, plus3 ], [ 1, 2, 3 ])).toEqual([ 2, 4, 6, 4, 5, 6 ])
})

---------------

aperture

aperture<N extends number, T>(n: N, list: T[]): Array<Tuple<T, N>> | []

It returns a new list, composed of consecutive n-tuples from a list.

const result = R.aperture(2, [1, 2, 3, 4])
// => [[1, 2], [2, 3], [3, 4]]

Try this R.aperture example in Rambda REPL

All TypeScript definitions
aperture<N extends number, T>(n: N, list: T[]): Array<Tuple<T, N>> | [];
aperture<N extends number>(n: N): <T>(list: T[]) => Array<Tuple<T, N>> | [];
R.aperture source
export function aperture(step, list){
  if (arguments.length === 1){
    return _list => aperture(step, _list)
  }
  if (step > list.length) return []
  let idx = 0
  const limit = list.length - (step - 1)
  const acc = new Array(limit)
  while (idx < limit){
    acc[ idx ] = list.slice(idx, idx + step)
    idx += 1
  }

  return acc
}
Tests
import { aperture } from './aperture.js'

const list = [ 1, 2, 3, 4, 5, 6, 7 ]

test('happy', () => {
  expect(aperture(1, list)).toEqual([ [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ], [ 6 ], [ 7 ] ])
  expect(aperture(2, list)).toEqual([
    [ 1, 2 ],
    [ 2, 3 ],
    [ 3, 4 ],
    [ 4, 5 ],
    [ 5, 6 ],
    [ 6, 7 ],
  ])
  expect(aperture(3, list)).toEqual([
    [ 1, 2, 3 ],
    [ 2, 3, 4 ],
    [ 3, 4, 5 ],
    [ 4, 5, 6 ],
    [ 5, 6, 7 ],
  ])
  expect(aperture(8, list)).toEqual([])
})

---------------

append

append<T>(xToAppend: T, iterable: T[]): T[]

It adds element x at the end of iterable.

const x = 'foo'

const result = R.append(x, ['bar', 'baz'])
// => ['bar', 'baz', 'foo']

Try this R.append example in Rambda REPL

All TypeScript definitions
append<T>(xToAppend: T, iterable: T[]): T[];
append<T, U>(xToAppend: T, iterable: IsFirstSubtypeOfSecond<T, U>[]) : U[];
append<T>(xToAppend: T): <U>(iterable: IsFirstSubtypeOfSecond<T, U>[]) => U[];
append<T>(xToAppend: T): (iterable: T[]) => T[];
R.append source
import { cloneList } from './_internals/cloneList.js'

export function append(x, input){
  if (arguments.length === 1) return _input => append(x, _input)

  if (typeof input === 'string') return input.split('').concat(x)

  const clone = cloneList(input)
  clone.push(x)

  return clone
}
Tests
import { append } from './append.js'

test('happy', () => {
  expect(append('tests', [ 'write', 'more' ])).toEqual([
    'write',
    'more',
    'tests',
  ])
})

test('append to empty array', () => {
  expect(append('tests')([])).toEqual([ 'tests' ])
})

test('with strings', () => {
  expect(append('o', 'fo')).toEqual([ 'f', 'o', 'o' ])
})

---------------

apply

apply<T = any>(fn: (...args: any[]) => T, args: any[]): T

It applies function fn to the list of arguments.

This is useful for creating a fixed-arity function from a variadic function. fn should be a bound function if context is significant.

const result = R.apply(Math.max, [42, -Infinity, 1337])
// => 1337

Try this R.apply example in Rambda REPL

All TypeScript definitions
apply<T = any>(fn: (...args: any[]) => T, args: any[]): T;
apply<T = any>(fn: (...args: any[]) => T): (args: any[]) => T;
R.apply source
export function apply(fn, args){
  if (arguments.length === 1){
    return _args => apply(fn, _args)
  }

  return fn.apply(this, args)
}
Tests
import { apply } from './apply.js'
import { bind } from './bind.js'
import { identity } from './identity.js'

test('happy', () => {
  expect(apply(identity, [ 1, 2, 3 ])).toBe(1)
})

test('applies function to argument list', () => {
  expect(apply(Math.max, [ 1, 2, 3, -99, 42, 6, 7 ])).toBe(42)
})

test('provides no way to specify context', () => {
  const obj = {
    method (){
      return this === obj
    },
  }
  expect(apply(obj.method, [])).toBeFalse()
  expect(apply(bind(obj.method, obj), [])).toBeTrue()
})

---------------

applyDiff

applyDiff<Output>(rules: ApplyDiffRule[], obj: object): Output

It changes paths in an object according to a list of operations. Valid operations are add, update and delete. Its use-case is while writing tests and you need to change the test data.

Note, that you cannot use update operation, if the object path is missing in the input object. Also, you cannot use add operation, if the object path has a value.

const obj = {a: {b:1, c:2}}
const rules = [
  {op: 'remove', path: 'a.c'},
  {op: 'add', path: 'a.d', value: 4},
  {op: 'update', path: 'a.b', value: 2},
]
const result = R.applyDiff(rules, Record<string, unknown>)
const expected = {a: {b: 2, d: 4}}

// => `result` is equal to `expected`

Try this R.applyDiff example in Rambda REPL

All TypeScript definitions
applyDiff<Output>(rules: ApplyDiffRule[], obj: object): Output;
applyDiff<Output>(rules: ApplyDiffRule[]): ( obj: object) => Output;
R.applyDiff source
import { createPath } from './_internals/createPath.js'
import { assocPathFn } from './assocPath.js'
import { path as pathModule } from './path.js'
const ALLOWED_OPERATIONS = [ 'remove', 'add', 'update' ]

export function removeAtPath(path, obj){
  const p = createPath(path)

  const len = p.length
  if (len === 0) return
  if (len === 1) return delete obj[ p[ 0 ] ]
  if (len === 2) return delete obj[ p[ 0 ] ][ p[ 1 ] ]
  if (len === 3) return delete obj[ p[ 0 ] ][ p[ 1 ] ][ p[ 2 ] ]
  if (len === 4) return delete obj[ p[ 0 ] ][ p[ 1 ] ][ p[ 2 ] ][ p[ 3 ] ]
  if (len === 5) return delete obj[ p[ 0 ] ][ p[ 1 ] ][ p[ 2 ] ][ p[ 3 ] ][ p[ 4 ] ]
  if (len === 6)
    return delete obj[ p[ 0 ] ][ p[ 1 ] ][ p[ 2 ] ][ p[ 3 ] ][ p[ 4 ] ][ p[ 5 ] ]

  if (len === 7)
    return delete obj[ p[ 0 ] ][ p[ 1 ] ][ p[ 2 ] ][ p[ 3 ] ][ p[ 4 ] ][ p[ 5 ] ][ p[ 6 ] ]

  if (len === 8)
    return delete obj[ p[ 0 ] ][ p[ 1 ] ][ p[ 2 ] ][ p[ 3 ] ][ p[ 4 ] ][ p[ 5 ] ][ p[ 6 ] ][ p[ 7 ] ]

  if (len === 9)
    return delete obj[ p[ 0 ] ][ p[ 1 ] ][ p[ 2 ] ][ p[ 3 ] ][ p[ 4 ] ][ p[ 5 ] ][ p[ 6 ] ][ p[ 7 ] ][ p[ 8 ] ]

  if (len === 10)
    return delete obj[ p[ 0 ] ][ p[ 1 ] ][ p[ 2 ] ][ p[ 3 ] ][ p[ 4 ] ][ p[ 5 ] ][ p[ 6 ] ][ p[ 7 ] ][ p[ 8 ] ][
      p[ 9 ]
    ]

}

export function applyDiff(rules, obj){
  if (arguments.length === 1) return _obj => applyDiff(rules, _obj)

  let clone = { ...obj }

  rules.forEach(({ op, path, value }) => {
    if (!ALLOWED_OPERATIONS.includes(op)) return
    if (op === 'add' && path && value !== undefined){
      if (pathModule(path, obj)) return

      clone = assocPathFn(
        path, value, clone
      )

      return
    }

    if (op === 'remove'){
      if (pathModule(path, obj) === undefined) return

      removeAtPath(path, clone)

      return
    }
    if (op === 'update' && path && value !== undefined){
      if (pathModule(path, obj) === undefined) return

      clone = assocPathFn(
        path, value, clone
      )

    }
  })

  return clone
}
Tests
import { applyDiff } from './applyDiff.js'

test('remove operation', () => {
  const rules = [
    {
      op   : 'remove',
      path : 'a.b',
    },
  ]
  const result = applyDiff(rules, {
    a : {
      b : 1,
      c : 2,
    },
  })
  expect(result).toEqual({ a : { c : 2 } })
})

test('update operation', () => {
  const rules = [
    {
      op    : 'update',
      path  : 'a.b',
      value : 3,
    },
    {
      op    : 'update',
      path  : 'a.c.1',
      value : 3,
    },
    {
      op    : 'update',
      path  : 'a.d',
      value : 3,
    },
  ]
  expect(applyDiff(rules, {
    a : {
      b : 1,
      c : [ 1, 2 ],
    },
  })).toEqual({
    a : {
      b : 3,
      c : [ 1, 3 ],
    },
  })
})

test('add operation', () => {
  const rules = [
    {
      op    : 'add',
      path  : 'a.b',
      value : 3,
    },
    {
      op    : 'add',
      path  : 'a.d',
      value : 3,
    },
  ]
  const result = applyDiff(rules, {
    a : {
      b : 1,
      c : 2,
    },
  })

  expect(result).toEqual({
    a : {
      b : 1,
      c : 2,
      d : 3,
    },
  })
})

---------------

applySpec

applySpec<Spec extends Record<string, AnyFunction>>(
  spec: Spec
): (
  ...args: Parameters<ValueOfRecord<Spec>>
) => { [Key in keyof Spec]: ReturnType<Spec[Key]> }

💥 The currying in this function works best with functions with 4 arguments or less. (arity of 4)

const fn = R.applySpec({
  sum: R.add,
  nested: { mul: R.multiply }
})
const result = fn(2, 4) 
// => { sum: 6, nested: { mul: 8 } }

Try this R.applySpec example in Rambda REPL

All TypeScript definitions
applySpec<Spec extends Record<string, AnyFunction>>(
  spec: Spec
): (
  ...args: Parameters<ValueOfRecord<Spec>>
) => { [Key in keyof Spec]: ReturnType<Spec[Key]> };
applySpec<T>(spec: any): (...args: unknown[]) => T;
R.applySpec source
import { isArray } from './_internals/isArray.js'

// recursively traverse the given spec object to find the highest arity function
export function __findHighestArity(spec, max = 0){
  for (const key in spec){
    if (spec.hasOwnProperty(key) === false || key === 'constructor') continue

    if (typeof spec[ key ] === 'object'){
      max = Math.max(max, __findHighestArity(spec[ key ]))
    }

    if (typeof spec[ key ] === 'function'){
      max = Math.max(max, spec[ key ].length)
    }
  }

  return max
}

function __filterUndefined(){
  const defined = []
  let i = 0
  const l = arguments.length
  while (i < l){
    if (typeof arguments[ i ] === 'undefined') break
    defined[ i ] = arguments[ i ]
    i++
  }

  return defined
}

function __applySpecWithArity(
  spec, arity, cache
){
  const remaining = arity - cache.length

  if (remaining === 1)
    return x =>
      __applySpecWithArity(
        spec, arity, __filterUndefined(...cache, x)
      )
  if (remaining === 2)
    return (x, y) =>
      __applySpecWithArity(
        spec, arity, __filterUndefined(
          ...cache, x, y
        )
      )
  if (remaining === 3)
    return (
      x, y, z
    ) =>
      __applySpecWithArity(
        spec, arity, __filterUndefined(
          ...cache, x, y, z
        )
      )
  if (remaining === 4)
    return (
      x, y, z, a
    ) =>
      __applySpecWithArity(
        spec,
        arity,
        __filterUndefined(
          ...cache, x, y, z, a
        )
      )
  if (remaining > 4)
    return (...args) =>
      __applySpecWithArity(
        spec, arity, __filterUndefined(...cache, ...args)
      )

  // handle spec as Array
  if (isArray(spec)){
    const ret = []
    let i = 0
    const l = spec.length
    for (; i < l; i++){
      // handle recursive spec inside array
      if (typeof spec[ i ] === 'object' || isArray(spec[ i ])){
        ret[ i ] = __applySpecWithArity(
          spec[ i ], arity, cache
        )
      }
      // apply spec to the key
      if (typeof spec[ i ] === 'function'){
        ret[ i ] = spec[ i ](...cache)
      }
    }

    return ret
  }

  // handle spec as Object
  const ret = {}
  // apply callbacks to each property in the spec object
  for (const key in spec){
    if (spec.hasOwnProperty(key) === false || key === 'constructor') continue

    // apply the spec recursively
    if (typeof spec[ key ] === 'object'){
      ret[ key ] = __applySpecWithArity(
        spec[ key ], arity, cache
      )
      continue
    }

    // apply spec to the key
    if (typeof spec[ key ] === 'function'){
      ret[ key ] = spec[ key ](...cache)
    }
  }

  return ret
}

export function applySpec(spec, ...args){
  // get the highest arity spec function, cache the result and pass to __applySpecWithArity
  const arity = __findHighestArity(spec)

  if (arity === 0){
    return () => ({})
  }
  const toReturn = __applySpecWithArity(
    spec, arity, args
  )

  return toReturn
}
Tests
import { applySpec as applySpecRamda, nAry } from 'ramda'

import {
  add,
  always,
  compose,
  dec,
  inc,
  map,
  path,
  prop,
  T,
} from '../rambda.js'
import { applySpec } from './applySpec.js'

test('different than Ramda when bad spec', () => {
  const result = applySpec({ sum : { a : 1 } })(1, 2)
  const ramdaResult = applySpecRamda({ sum : { a : 1 } })(1, 2)
  expect(result).toEqual({})
  expect(ramdaResult).toEqual({ sum : { a : {} } })
})

test('works with empty spec', () => {
  expect(applySpec({})()).toEqual({})
  expect(applySpec([])(1, 2)).toEqual({})
  expect(applySpec(null)(1, 2)).toEqual({})
})

test('works with unary functions', () => {
  const result = applySpec({
    v : inc,
    u : dec,
  })(1)
  const expected = {
    v : 2,
    u : 0,
  }
  expect(result).toEqual(expected)
})

test('works with binary functions', () => {
  const result = applySpec({ sum : add })(1, 2)
  expect(result).toEqual({ sum : 3 })
})

test('works with nested specs', () => {
  const result = applySpec({
    unnested : always(0),
    nested   : { sum : add },
  })(1, 2)
  const expected = {
    unnested : 0,
    nested   : { sum : 3 },
  }
  expect(result).toEqual(expected)
})

test('works with arrays of nested specs', () => {
  const result = applySpec({
    unnested : always(0),
    nested   : [ { sum : add } ],
  })(1, 2)

  expect(result).toEqual({
    unnested : 0,
    nested   : [ { sum : 3 } ],
  })
})

test('works with arrays of spec objects', () => {
  const result = applySpec([ { sum : add } ])(1, 2)

  expect(result).toEqual([ { sum : 3 } ])
})

test('works with arrays of functions', () => {
  const result = applySpec([ map(prop('a')), map(prop('b')) ])([
    {
      a : 'a1',
      b : 'b1',
    },
    {
      a : 'a2',
      b : 'b2',
    },
  ])
  const expected = [
    [ 'a1', 'a2' ],
    [ 'b1', 'b2' ],
  ]
  expect(result).toEqual(expected)
})

test('works with a spec defining a map key', () => {
  expect(applySpec({ map : prop('a') })({ a : 1 })).toEqual({ map : 1 })
})

test('cannot retains the highest arity', () => {
  const f = applySpec({
    f1 : nAry(2, T),
    f2 : nAry(5, T),
  })
  const fRamda = applySpecRamda({
    f1 : nAry(2, T),
    f2 : nAry(5, T),
  })
  expect(f).toHaveLength(0)
  expect(fRamda).toHaveLength(5)
})

test('returns a curried function', () => {
  expect(applySpec({ sum : add })(1)(2)).toEqual({ sum : 3 })
})

// Additional tests
// ============================================
test('arity', () => {
  const spec = {
    one   : x1 => x1,
    two   : (x1, x2) => x1 + x2,
    three : (
      x1, x2, x3
    ) => x1 + x2 + x3,
  }
  expect(applySpec(
    spec, 1, 2, 3
  )).toEqual({
    one   : 1,
    two   : 3,
    three : 6,
  })
})

test('arity over 5 arguments', () => {
  const spec = {
    one   : x1 => x1,
    two   : (x1, x2) => x1 + x2,
    three : (
      x1, x2, x3
    ) => x1 + x2 + x3,
    four : (
      x1, x2, x3, x4
    ) => x1 + x2 + x3 + x4,
    five : (
      x1, x2, x3, x4, x5
    ) => x1 + x2 + x3 + x4 + x5,
  }
  expect(applySpec(
    spec, 1, 2, 3, 4, 5
  )).toEqual({
    one   : 1,
    two   : 3,
    three : 6,
    four  : 10,
    five  : 15,
  })
})

test('curried', () => {
  const spec = {
    one   : x1 => x1,
    two   : (x1, x2) => x1 + x2,
    three : (
      x1, x2, x3
    ) => x1 + x2 + x3,
  }
  expect(applySpec(spec)(1)(2)(3)).toEqual({
    one   : 1,
    two   : 3,
    three : 6,
  })
})

test('curried over 5 arguments', () => {
  const spec = {
    one   : x1 => x1,
    two   : (x1, x2) => x1 + x2,
    three : (
      x1, x2, x3
    ) => x1 + x2 + x3,
    four : (
      x1, x2, x3, x4
    ) => x1 + x2 + x3 + x4,
    five : (
      x1, x2, x3, x4, x5
    ) => x1 + x2 + x3 + x4 + x5,
  }
  expect(applySpec(spec)(1)(2)(3)(4)(5)).toEqual({
    one   : 1,
    two   : 3,
    three : 6,
    four  : 10,
    five  : 15,
  })
})

test('undefined property', () => {
  const spec = { prop : path([ 'property', 'doesnt', 'exist' ]) }
  expect(applySpec(spec, {})).toEqual({ prop : undefined })
})

test('restructure json object', () => {
  const spec = {
    id          : path('user.id'),
    name        : path('user.firstname'),
    profile     : path('user.profile'),
    doesntExist : path('user.profile.doesntExist'),
    info        : { views : compose(inc, prop('views')) },
    type        : always('playa'),
  }

  const data = {
    user : {
      id        : 1337,
      firstname : 'john',
      lastname  : 'shaft',
      profile   : 'shaft69',
    },
    views : 42,
  }

  expect(applySpec(spec, data)).toEqual({
    id          : 1337,
    name        : 'john',
    profile     : 'shaft69',
    doesntExist : undefined,
    info        : { views : 43 },
    type        : 'playa',
  })
})

---------------

applyTo

applyTo<T, U>(el: T, fn: (t: T) => U): U
const result = R.applyTo(
  1,
  x => x + 1
)
// => 2

Try this R.applyTo example in Rambda REPL

All TypeScript definitions
applyTo<T, U>(el: T, fn: (t: T) => U): U;
applyTo<T>(el: T): <U>(fn: (t: T) => U) => U;
R.applyTo source
export function applyTo(input, fn){
  if (arguments.length === 1){
    return _fn => applyTo(input, _fn)
  }

  return fn(input)
}
Tests
import { applyTo } from './applyTo.js'
import { multiply } from './multiply.js'

test('happy', () => {
  expect(applyTo(21, multiply(2))).toBe(42)
})

---------------

ascend

ascend<T>(fn: (obj: T) => Ord, a: T, b: T): Ordering
const result = R.sort(R.descend(x => x), [2, 1])
// => [1, 2]

Try this R.ascend example in Rambda REPL

All TypeScript definitions
ascend<T>(fn: (obj: T) => Ord, a: T, b: T): Ordering;
ascend<T>(fn: (obj: T) => Ord): (a: T, b: T) => Ordering;
R.ascend source
export function createCompareFunction(
  a, b, winner, loser
){
  if (a === b) return 0

  return a < b ? winner : loser
}

export function ascend(
  getFunction, a, b
){
  if (arguments.length === 1){
    return (_a, _b) => ascend(
      getFunction, _a, _b
    )
  }
  const aValue = getFunction(a)
  const bValue = getFunction(b)

  return createCompareFunction(
    aValue, bValue, -1, 1
  )
}
Tests
import { ascend } from './ascend.js'
import { descend } from './descend.js'
import { sort } from './sort.js'

const people = [
  {
    name : 'Emma',
    age  : 70,
  },
  {
    name : 'Peter',
    age  : 78,
  },
  {
    name : 'Mikhail',
    age  : 62,
  },
]

test('ascend', () => {
  const result = sort(ascend(x => x?.age),
    people)
  const expected = [
    {
      name : 'Mikhail',
      age  : 62,
    },
    {
      name : 'Emma',
      age  : 70,
    },
    {
      name : 'Peter',
      age  : 78,
    },
  ]
  expect(result).toEqual(expected)
})

test('descend', () => {
  const result = sort(descend(x => x?.age),
    people)
  const expected = [
    {
      name : 'Peter',
      age  : 78,
    },
    {
      name : 'Emma',
      age  : 70,
    },
    {
      name : 'Mikhail',
      age  : 62,
    },
  ]

  expect(result).toEqual(expected)
})

---------------

assoc

assoc<K extends PropertyKey>(prop: K): {
  <T>(val: T): <U extends Record<K, T>>(obj: U) => U

It makes a shallow clone of obj with setting or overriding the property prop with newValue.

💥 This copies and flattens prototype properties onto the new object as well. All non-primitive properties are copied by reference.

R.assoc('c', 3, {a: 1, b: 2})
// => {a: 1, b: 2, c: 3}

Try this R.assoc example in Rambda REPL

All TypeScript definitions
assoc<K extends PropertyKey>(prop: K): {
  <T>(val: T): <U extends Record<K, T>>(obj: U) => U;
  <U extends Record<K, T>, T>(val: T, obj: U): U;
};
assoc<T, K extends PropertyKey>(prop: K, val: T): {
  <U>(obj: U): U extends Record<K, any> ? U[K] extends T ? U : Record<K, T> & Omit<U, K> : U & Record<K, T>;
};
assoc<U, K extends keyof U, T extends U[K]>(prop: K, val: T, obj: U): U;
R.assoc source
import { curry } from './curry.js'

export function assocFn(
  prop, newValue, obj
){
  return Object.assign(
    {}, obj, { [ prop ] : newValue }
  )
}

export const assoc = curry(assocFn)
Tests
import { assoc } from './assoc.js'

test('adds a key to an empty object', () => {
  expect(assoc(
    'a', 1, {}
  )).toEqual({ a : 1 })
})

test('adds a key to a non-empty object', () => {
  expect(assoc(
    'b', 2, { a : 1 }
  )).toEqual({
    a : 1,
    b : 2,
  })
})

test('adds a key to a non-empty object - curry case 1', () => {
  expect(assoc('b', 2)({ a : 1 })).toEqual({
    a : 1,
    b : 2,
  })
})

test('adds a key to a non-empty object - curry case 2', () => {
  expect(assoc('b')(2, { a : 1 })).toEqual({
    a : 1,
    b : 2,
  })
})

test('adds a key to a non-empty object - curry case 3', () => {
  const result = assoc('b')(2)({ a : 1 })

  expect(result).toEqual({
    a : 1,
    b : 2,
  })
})

test('changes an existing key', () => {
  expect(assoc(
    'a', 2, { a : 1 }
  )).toEqual({ a : 2 })
})

test('undefined is considered an empty object', () => {
  expect(assoc(
    'a', 1, undefined
  )).toEqual({ a : 1 })
})

test('null is considered an empty object', () => {
  expect(assoc(
    'a', 1, null
  )).toEqual({ a : 1 })
})

test('value can be null', () => {
  expect(assoc(
    'a', null, null
  )).toEqual({ a : null })
})

test('value can be undefined', () => {
  expect(assoc(
    'a', undefined, null
  )).toEqual({ a : undefined })
})

test('assignment is shallow', () => {
  expect(assoc(
    'a', { b : 2 }, { a : { c : 3 } }
  )).toEqual({ a : { b : 2 } })
})

---------------

assocPath

assocPath<Output>(path: Path, newValue: any, obj: object): Output

It makes a shallow clone of obj with setting or overriding with newValue the property found with path.

const path = 'b.c'
const newValue = 2
const obj = { a: 1 }

const result = R.assocPath(path, newValue, obj)
// => { a : 1, b : { c : 2 }}

Try this R.assocPath example in Rambda REPL

All TypeScript definitions
assocPath<Output>(path: Path, newValue: any, obj: object): Output;
assocPath<Output>(path: Path, newValue: any): (obj: object) => Output;
assocPath<Output>(path: Path): (newValue: any) => (obj: object) => Output;
R.assocPath source
import { cloneList } from './_internals/cloneList.js'
import { createPath } from './_internals/createPath.js'
import { isArray } from './_internals/isArray.js'
import { isIndexInteger } from './_internals/isInteger.js'
import { assocFn } from './assoc.js'
import { curry } from './curry.js'

export function assocPathFn(
  path, newValue, input
){
  const pathArrValue = createPath(path)
  if (pathArrValue.length === 0) return newValue

  const index = pathArrValue[ 0 ]
  if (pathArrValue.length > 1){
    const condition =
      typeof input !== 'object' ||
      input === null ||
      !input.hasOwnProperty(index)

    const nextInput = condition ?
      isIndexInteger(pathArrValue[ 1 ]) ?
        [] :
        {} :
      input[ index ]

    newValue = assocPathFn(
      Array.prototype.slice.call(pathArrValue, 1),
      newValue,
      nextInput
    )
  }

  if (isIndexInteger(index) && isArray(input)){
    const arr = cloneList(input)
    arr[ index ] = newValue

    return arr
  }

  return assocFn(
    index, newValue, input
  )
}

export const assocPath = curry(assocPathFn)
Tests
import { assocPathFn } from './assocPath.js'

test('happy', () => {
  const path = 'a.c.1'
  const input = {
    a : {
      b : 1,
      c : [ 1, 2 ],
    },
  }
  assocPathFn(
    path, 3, input
  )
  expect(input).toEqual({
    a : {
      b : 1,
      c : [ 1, 2 ],
    },
  })
})

test('string can be used as path input', () => {
  const testObj = {
    a : [ { b : 1 }, { b : 2 } ],
    d : 3,
  }
  const result1 = assocPathFn(
    [ 'a', 0, 'b' ], 10, testObj
  )
  const result2 = assocPathFn(
    'a.0.b', 10, testObj
  )

  const expected = {
    a : [ { b : 10 }, { b : 2 } ],
    d : 3,
  }
  expect(result1).toEqual(expected)
  expect(result2).toEqual(expected)
})

test('difference with ramda - doesn\'t overwrite primitive values with keys in the path', () => {
  const obj = { a : 'str' }
  const result = assocPathFn(
    [ 'a', 'b' ], 42, obj
  )

  expect(result).toEqual({
    a : {
      0 : 's',
      1 : 't',
      2 : 'r',
      b : 42,
    },
  })
})

test('adds a key to an empty object', () => {
  expect(assocPathFn(
    [ 'a' ], 1, {}
  )).toEqual({ a : 1 })
})

test('adds a key to a non-empty object', () => {
  expect(assocPathFn(
    'b', 2, { a : 1 }
  )).toEqual({
    a : 1,
    b : 2,
  })
})

test('adds a nested key to a non-empty object', () => {
  expect(assocPathFn(
    'b.c', 2, { a : 1 }
  )).toEqual({
    a : 1,
    b : { c : 2 },
  })
})

test('adds a nested key to a nested non-empty object', () => {
  expect(assocPathFn('b.d',
    3,{
    a : 1,
    b : { c : 2 },
  })).toEqual({
    a : 1,
    b : {
      c : 2,
      d : 3,
    },
  })
})

test('adds a key to a non-empty object', () => {
  expect(assocPathFn('b', 2, { a : 1 })).toEqual({
    a : 1,
    b : 2,
  })
})

test('adds a nested key to a non-empty object', () => {
  expect(assocPathFn('b.c', 2, { a : 1 })).toEqual({
    a : 1,
    b : { c : 2 },
  })
})

test('changes an existing key', () => {
  expect(assocPathFn(
    'a', 2, { a : 1 }
  )).toEqual({ a : 2 })
})

test('undefined is considered an empty object', () => {
  expect(assocPathFn(
    'a', 1, undefined
  )).toEqual({ a : 1 })
})

test('null is considered an empty object', () => {
  expect(assocPathFn(
    'a', 1, null
  )).toEqual({ a : 1 })
})

test('value can be null', () => {
  expect(assocPathFn(
    'a', null, null
  )).toEqual({ a : null })
})

test('value can be undefined', () => {
  expect(assocPathFn(
    'a', undefined, null
  )).toEqual({ a : undefined })
})

test('assignment is shallow', () => {
  expect(assocPathFn(
    'a', { b : 2 }, { a : { c : 3 } }
  )).toEqual({ a : { b : 2 } })
})

test('empty array as path', () => {
  const result = assocPathFn(
    [], 3, {
      a : 1,
      b : 2,
    }
  )
  expect(result).toBe(3)
})

test('happy', () => {
  const expected = { foo : { bar : { baz : 42 } } }
  const result = assocPathFn(
    [ 'foo', 'bar', 'baz' ], 42, { foo : null }
  )
  expect(result).toEqual(expected)
})

---------------

binary

binary<T extends (...arg: any[]) => any>(fn: T): (...args: any[]) => ReturnType<T>
const result = R.binary(
  (a, b, c) => a + b + c,
)(1, 2, 3, 4)
// => 3

Try this R.binary example in Rambda REPL

All TypeScript definitions
binary<T extends (...arg: any[]) => any>(fn: T): (...args: any[]) => ReturnType<T>;
R.binary source
export function binary(fn){
  if (fn.length <= 2) return fn

  return (a, b) => fn(a, b)
}
Tests
import { binary } from './binary.js'

test('happy', () => {
  const result = binary(function (
    x, y, z
  ){
    expect(arguments).toHaveLength(2)
    expect(z).toBeUndefined()
    expect(x).toBe(10)
    expect(y).toBe(20)

    return x + y
  })(
    10, 20, 30
  )
  expect(result).toBe(30)
})

---------------

bind

bind<F extends AnyFunction, T>(fn: F, thisObj: T): (...args: Parameters<F>) => ReturnType<F>

Creates a function that is bound to a context.

💥 R.bind does not provide the additional argument-binding capabilities of Function.prototype.bind.

const log = R.bind(console.log, console)
const result = R.pipe(
  R.assoc('a', 2), 
  R.tap(log), 
  R.assoc('a', 3)
)({a: 1}); 
// => result - `{a: 3}`
// => console log - `{a: 2}`

Try this R.bind example in Rambda REPL

All TypeScript definitions
bind<F extends AnyFunction, T>(fn: F, thisObj: T): (...args: Parameters<F>) => ReturnType<F>;
bind<F extends AnyFunction, T>(fn: F): (thisObj: T) => (...args: Parameters<F>) => ReturnType<F>;
R.bind source
import { curryN } from './curryN.js'

export function bind(fn, thisObj){
  if (arguments.length === 1){
    return _thisObj => bind(fn, _thisObj)
  }

  return curryN(fn.length, (...args) => fn.apply(thisObj, args))
}
Tests
import { bind } from './bind.js'

function Foo(x){
  this.x = x
}
function add(x){
  return this.x + x
}
function Bar(x, y){
  this.x = x
  this.y = y
}
Bar.prototype = new Foo()
Bar.prototype.getX = function (){
  return 'prototype getX'
}

test('returns a function', () => {
  expect(typeof bind(add)(Foo)).toBe('function')
})

test('returns a function bound to the specified context object', () => {
  const f = new Foo(12)
  function isFoo(){
    return this instanceof Foo
  }
  const isFooBound = bind(isFoo, f)
  expect(isFoo()).toBeFalse()
  expect(isFooBound()).toBeTrue()
})

test('works with built-in types', () => {
  const abc = bind(String.prototype.toLowerCase, 'ABCDEFG')
  expect(typeof abc).toBe('function')
  expect(abc()).toBe('abcdefg')
})

test('works with user-defined types', () => {
  const f = new Foo(12)
  function getX(){
    return this.x
  }
  const getXFooBound = bind(getX, f)
  expect(getXFooBound()).toBe(12)
})

test('works with plain objects', () => {
  const pojso = { x : 100 }
  function incThis(){
    return this.x + 1
  }
  const incPojso = bind(incThis, pojso)
  expect(typeof incPojso).toBe('function')
  expect(incPojso()).toBe(101)
})

test('does not interfere with existing object methods', () => {
  const b = new Bar('a', 'b')
  function getX(){
    return this.x
  }
  const getXBarBound = bind(getX, b)
  expect(b.getX()).toBe('prototype getX')
  expect(getXBarBound()).toBe('a')
})

test('preserves arity', () => {
  const f0 = function (){
    return 0
  }
  const f1 = function (a){
    return a
  }
  const f2 = function (a, b){
    return a + b
  }
  const f3 = function (
    a, b, c
  ){
    return a + b + c
  }

  expect(bind(f0, {})).toHaveLength(0)
  expect(bind(f1, {})).toHaveLength(1)
  expect(bind(f2, {})).toHaveLength(2)
  expect(bind(f3, {})).toHaveLength(3)
})

---------------

both

both(pred1: Pred, pred2: Pred): Pred

It returns a function with input argument.

This function will return true, if both firstCondition and secondCondition return true when input is passed as their argument.

const firstCondition = x => x > 10
const secondCondition = x => x < 20
const fn = R.both(firstCondition, secondCondition)

const result = [fn(15), fn(30)]
// => [true, false]

Try this R.both example in Rambda REPL

All TypeScript definitions
both(pred1: Pred, pred2: Pred): Pred;
both<T>(pred1: Predicate<T>, pred2: Predicate<T>): Predicate<T>;
both<T>(pred1: Predicate<T>): (pred2: Predicate<T>) => Predicate<T>;
both(pred1: Pred): (pred2: Pred) => Pred;
R.both source
export function both(f, g){
  if (arguments.length === 1) return _g => both(f, _g)

  return (...input) => f(...input) && g(...input)
}
Tests
import { both } from './both.js'

const firstFn = val => val > 0
const secondFn = val => val < 10

test('with curry', () => {
  expect(both(firstFn)(secondFn)(17)).toBeFalse()
})

test('without curry', () => {
  expect(both(firstFn, secondFn)(7)).toBeTrue()
})

test('with multiple inputs', () => {
  const between = function (
    a, b, c
  ){
    return a < b && b < c
  }
  const total20 = function (
    a, b, c
  ){
    return a + b + c === 20
  }
  const fn = both(between, total20)
  expect(fn(
    5, 7, 8
  )).toBeTrue()
})

test('skip evaluation of the second expression', () => {
  let effect = 'not evaluated'
  const F = function (){
    return false
  }
  const Z = function (){
    effect = 'Z got evaluated'
  }
  both(F, Z)()

  expect(effect).toBe('not evaluated')
})

---------------

call

call<T extends (...args: any[]) => any>(fn: T, ...args: Parameters<T>): ReturnType<T>
const result = R.call(
  (a, b) => a + b,
  1,
  2
)
// => 3

Try this R.call example in Rambda REPL

All TypeScript definitions
call<T extends (...args: any[]) => any>(fn: T, ...args: Parameters<T>): ReturnType<T>;
R.call source
export const call = (fn, ...inputs) => fn(...inputs)
Tests
import { bind } from './bind.js'
import { call } from './call.js'

test('happy', () => {
  expect(call(
    Math.max, 1, 2, 3, -99, 42, 6, 7
  )).toBe(42)
})

test('accepts one or more arguments', () => {
  const fn = function (){
    return arguments.length
  }
  expect(call(fn)).toBe(0)
  expect(call(fn, 'x')).toBe(1)
  expect(call(
    fn, 'x', 'y'
  )).toBe(2)
  expect(call(
    fn, 'x', 'y', 'z'
  )).toBe(3)
})

test('provides no way to specify context', () => {
  var obj = {
    method (){
      return this === obj
    },
  }
  expect(call(obj.method)).toBe(false)
  expect(call(bind(obj.method, obj))).toBe(true)
})

---------------

chain

chain<T, U>(fn: (n: T) => U[], list: T[]): U[]

The method is also known as flatMap.

const duplicate = n => [ n, n ]
const list = [ 1, 2, 3 ]

const result = chain(duplicate, list)
// => [ 1, 1, 2, 2, 3, 3 ]

Try this R.chain example in Rambda REPL

All TypeScript definitions
chain<T, U>(fn: (n: T) => U[], list: T[]): U[];
chain<T, U>(fn: (n: T) => U[]): (list: T[]) => U[];
R.chain source
export function chain(fn, list){
  if (arguments.length === 1){
    return _list => chain(fn, _list)
  }

  return [].concat(...list.map(fn))
}
Tests
import { chain as chainRamda } from 'ramda'

import { chain } from './chain.js'

const duplicate = n => [ n, n ]

test('happy', () => {
  const fn = x => [ x * 2 ]
  const list = [ 1, 2, 3 ]

  const result = chain(fn, list)

  expect(result).toEqual([ 2, 4, 6 ])
})

test('maps then flattens one level', () => {
  expect(chain(duplicate, [ 1, 2, 3 ])).toEqual([ 1, 1, 2, 2, 3, 3 ])
})

test('maps then flattens one level - curry', () => {
  expect(chain(duplicate)([ 1, 2, 3 ])).toEqual([ 1, 1, 2, 2, 3, 3 ])
})

test('flattens only one level', () => {
  const nest = n => [ [ n ] ]
  expect(chain(nest, [ 1, 2, 3 ])).toEqual([ [ 1 ], [ 2 ], [ 3 ] ])
})

test('can compose', () => {
  function dec(x){
    return [ x - 1 ]
  }
  function times2(x){
    return [ x * 2 ]
  }

  const mdouble = chain(times2)
  const mdec = chain(dec)
  expect(mdec(mdouble([ 10, 20, 30 ]))).toEqual([ 19, 39, 59 ])
})

test('@types/ramda broken test', () => {
  const score = {
    maths   : 90,
    physics : 80,
  }

  const calculateTotal = score => {
    const { maths, physics } = score

    return maths + physics
  }

  const assocTotalToScore = (total, score) => ({
    ...score,
    total,
  })

  const calculateAndAssocTotalToScore = chainRamda(assocTotalToScore,
    calculateTotal)
  expect(() =>
    calculateAndAssocTotalToScore(score)).toThrowErrorMatchingInlineSnapshot('"fn(...) is not a function"')
})

---------------

clamp

clamp(min: number, max: number, input: number): number

Restrict a number input to be within min and max limits.

If input is bigger than max, then the result is max.

If input is smaller than min, then the result is min.

const result = [
  R.clamp(0, 10, 5), 
  R.clamp(0, 10, -1),
  R.clamp(0, 10, 11)
]
// => [5, 0, 10]

Try this R.clamp example in Rambda REPL

All TypeScript definitions
clamp(min: number, max: number, input: number): number;
clamp(min: number, max: number): (input: number) => number;
R.clamp source
import { curry } from './curry.js'

function clampFn(
  min, max, input
){
  if (min > max){
    throw new Error('min must not be greater than max in clamp(min, max, value)')
  }
  if (input >= min && input <= max) return input

  if (input > max) return max
  if (input < min) return min
}

export const clamp = curry(clampFn)
Tests
import { clamp } from './clamp.js'

test('when min is greater than max', () => {
  expect(() => clamp(
    -5, -10, 5
  )).toThrowErrorMatchingInlineSnapshot('"min must not be greater than max in clamp(min, max, value)"')
})

test('rambda specs', () => {
  expect(clamp(
    1, 10, 0
  )).toBe(1)
  expect(clamp(
    3, 12, 1
  )).toBe(3)
  expect(clamp(
    -15, 3, -100
  )).toBe(-15)
  expect(clamp(
    1, 10, 20
  )).toBe(10)
  expect(clamp(
    3, 12, 23
  )).toBe(12)
  expect(clamp(
    -15, 3, 16
  )).toBe(3)
  expect(clamp(
    1, 10, 4
  )).toBe(4)
  expect(clamp(
    3, 12, 6
  )).toBe(6)
  expect(clamp(
    -15, 3, 0
  )).toBe(0)
})

---------------

clone

clone<T>(input: T): T

It creates a deep copy of the input, which may contain (nested) Arrays and Objects, Numbers, Strings, Booleans and Dates.

💥 It doesn't work with very specific types, such as MongoDB's ObjectId.

const objects = [{a: 1}, {b: 2}];
const objectsClone = R.clone(objects);

const result = [
  R.equals(objects, objectsClone),
  R.equals(objects[0], objectsClone[0]),
] // => [ true, true ]

Try this R.clone example in Rambda REPL

All TypeScript definitions
clone<T>(input: T): T;
clone<T>(input: T[]): T[];
R.clone source
import { isArray } from './_internals/isArray.js'

export function clone(input){
  const out = isArray(input) ? Array(input.length) : {}
  if (input && input.getTime) return new Date(input.getTime())

  for (const key in input){
    const v = input[ key ]
    out[ key ] =
      typeof v === 'object' && v !== null ?
        v.getTime ?
          new Date(v.getTime()) :
          clone(v) :
        v
  }

  return out
}
Tests
import assert from 'assert'
import { clone as cloneRamda } from 'ramda'

import {
  compareCombinations,
  EXTRA_BUILD_IN_OBJECTS,
  FALSY_VALUES,
} from './_internals/testUtils.js'
import { clone } from './clone.js'
import { equals } from './equals.js'

test('with array', () => {
  const arr = [
    {
      b : 2,
      c : 'foo',
      d : [ 1, 2, 3 ],
    },
    1,
    new Date(),
    null,
  ]
  expect(clone(arr)).toEqual(arr)
})

test('with object', () => {
  const obj = {
    a : 1,
    b : 2,
    c : 3,
    d : [ 1, 2, 3 ],
    e : new Date(),
  }
  expect(clone(obj)).toEqual(obj)
})

test('with date', () => {
  const date = new Date(
    2014, 10, 14, 23, 59, 59, 999
  )

  const cloned = clone(date)
  assert.notStrictEqual(date, cloned)
  expect(cloned).toEqual(new Date(
    2014, 10, 14, 23, 59, 59, 999
  ))

  expect(cloned.getDay()).toBe(5)
})

test('with R.equals', () => {
  const objects = [ { a : 1 }, { b : 2 } ]

  const objectsClone = clone(objects)

  const result = [
    equals(objects, objectsClone),
    equals(objects[ 0 ], objectsClone[ 0 ]),
  ]
  expect(result).toEqual([ true, true ])
})

describe('brute force', () => {
  const possibleInputs = [ ...FALSY_VALUES, ...EXTRA_BUILD_IN_OBJECTS ]
  compareCombinations({
    fn         : clone,
    fnRamda    : cloneRamda,
    firstInput : possibleInputs,
    callback   : errorsCounters => {
      expect(errorsCounters).toMatchInlineSnapshot(`
        {
          "ERRORS_MESSAGE_MISMATCH": 0,
          "ERRORS_TYPE_MISMATCH": 0,
          "RESULTS_MISMATCH": 15,
          "SHOULD_NOT_THROW": 0,
          "SHOULD_THROW": 0,
          "TOTAL_TESTS": 15,
        }
      `)
    },
  })
})

---------------

collectBy

collectBy<T, K extends PropertyKey>(keyFn: (value: T) => K, list: T[]): T[][]
const result = R.collectBy(
  x => x % 2,
  [1, 2, 3, 4]
)
// => [[2, 4], [1, 3]]

Try this R.collectBy example in Rambda REPL

All TypeScript definitions
collectBy<T, K extends PropertyKey>(keyFn: (value: T) => K, list: T[]): T[][];
collectBy<T, K extends PropertyKey>(keyFn: (value: T) => K): (list: T[]) => T[][];
R.collectBy source
import { reduce } from './reduce.js'

export function collectBy(fn, list){
  if (arguments.length === 1){
    return _list => collectBy(fn, _list)
  }

  const group = reduce(
    (o, x) => {
      const tag = fn(x)
      if (o[ tag ] === undefined){
        o[ tag ] = []
      }
      o[ tag ].push(x)

      return o
    },
    {},
    list
  )
  const newList = []
  for (const tag in group){
    newList.push(group[ tag ])
  }

  return newList
}
Tests
import fc from 'fast-check'
import {
  all,
  compose,
  difference,
  equals,
  head,
  identity,
  is,
  isEmpty,
  length,
  uniq,
  unnest,
} from 'rambdax'

import { collectBy } from './collectBy.js'

test('returns a list of lists', () => {
  fc.assert(fc.property(fc.array(fc.nat()), xs => {
    const check = all(is(Array))
    const ys = collectBy(identity)(xs)

    return check(ys)
  }))
})

test('groups items but neither adds new ones nor removes any', () => {
  fc.assert(fc.property(fc.array(fc.nat()), xs => {
    const check = compose(
      isEmpty, difference(xs), unnest
    )
    const ys = collectBy(identity)(xs)

    return check(ys)
  }))
})

test('groups related items together', () => {
  fc.assert(fc.property(fc.array(fc.boolean()), xs => {
    const ys = collectBy(identity)(xs)
    const check = all(compose(
      equals(1), length, uniq
    ))

    return check(ys)
  }))
})

test('invokes the tag function for each item in the list', () => {
  fc.assert(fc.property(fc.array(fc.nat()), xs => {
    const id = jest.fn(x => 42)
    collectBy(id)(xs)
    const check = compose(isEmpty, difference(xs))

    return check(id.mock.calls.map(call => call[ 0 ]))
  }))
})

test('groups items according to the tag value', () => {
  fc.assert(fc.property(fc.array(fc.nat()), xs => {
    const ys = collectBy(x => 42)(xs)
    const check = compose(
      isEmpty, difference(xs), head
    )

    return isEmpty(xs) && isEmpty(ys) ? true : check(ys)
  }))
})

---------------

comparator

comparator<T>(pred: (a: T, b: T) => boolean): (x: T, y: T) => Ordering

It returns a comparator function that can be used in sort method.

const result = R.sort(
  R.comparator((a, b) => a.x < b.x),
  [{x: 2}, {x: 1}]
)
// => [{x: 1}, {x: 2}]

Try this R.comparator example in Rambda REPL

All TypeScript definitions
comparator<T>(pred: (a: T, b: T) => boolean): (x: T, y: T) => Ordering;
R.comparator source
export function comparator(fn){
  return function (a, b){
    return fn(a, b) ? -1 : fn(b, a) ? 1 : 0
  }
}
Tests
import { comparator } from './comparator.js'

test('happy', () => {
  expect([ 3, 1, 8, 1, 2, 5 ].sort(comparator((a, b) => a < b))).toEqual([
    1, 1, 2, 3, 5, 8,
  ])
})

---------------

complement

complement<T extends any[]>(predicate: (...args: T) => unknown): (...args: T) => boolean

It returns inverted version of origin function that accept input as argument.

The return value of inverted is the negative boolean value of origin(input).

const origin = x => x > 5
const inverted = complement(origin)

const result = [
  origin(7),
  inverted(7)
] => [ true, false ]

Try this R.complement example in Rambda REPL

All TypeScript definitions
complement<T extends any[]>(predicate: (...args: T) => unknown): (...args: T) => boolean;
R.complement source
export function complement(fn){
  return (...input) => !fn(...input)
}
Tests
import { complement } from './complement.js'

test('happy', () => {
  const fn = complement(x => x.length === 0)

  expect(fn([ 1, 2, 3 ])).toBeTrue()
})

test('with multiple parameters', () => {
  const between = function (
    a, b, c
  ){
    return a < b && b < c
  }
  const f = complement(between)
  expect(f(
    4, 5, 11
  )).toBeFalse()
  expect(f(
    12, 2, 6
  )).toBeTrue()
})

---------------

compose

compose<TArgs extends any[], R1, R2, R3, R4, R5, R6, R7, TResult>(
  ...func: [
      fnLast: (a: any) => TResult,
      ...func: Array<(a: any) => any>,
      f7: (a: R6) => R7,
      f6: (a: R5) => R6,
      f5: (a: R4) => R5,
      f4: (a: R3) => R4,
      f3: (a: R2) => R3,
      f2: (a: R1) => R2,
      f1: (...args: TArgs) => R1
  ]
): (...args: TArgs) => TResult

It performs right-to-left function composition.

const result = R.compose(
  R.map(x => x * 2),
  R.filter(x => x > 2)
)([1, 2, 3, 4])

// => [6, 8]

Try this R.compose example in Rambda REPL

All TypeScript definitions
compose<TArgs extends any[], R1, R2, R3, R4, R5, R6, R7, TResult>(
  ...func: [
      fnLast: (a: any) => TResult,
      ...func: Array<(a: any) => any>,
      f7: (a: R6) => R7,
      f6: (a: R5) => R6,
      f5: (a: R4) => R5,
      f4: (a: R3) => R4,
      f3: (a: R2) => R3,
      f2: (a: R1) => R2,
      f1: (...args: TArgs) => R1
  ]
): (...args: TArgs) => TResult;
compose<TArgs extends any[], R1, R2, R3, R4, R5, R6, R7, TResult>(
  f7: (a: R6) => R7,
  f6: (a: R5) => R6,
  f5: (a: R4) => R5,
  f4: (a: R3) => R4,
  f3: (a: R2) => R3,
  f2: (a: R1) => R2,
  f1: (...args: TArgs) => R1
): (...args: TArgs) => R7;
compose<TArgs extends any[], R1, R2, R3, R4, R5, R6, R7>(
  f7: (a: R6) => R7,
  f6: (a: R5) => R6,
  f5: (a: R4) => R5,
  f4: (a: R3) => R4,
  f3: (a: R2) => R3,
  f2: (a: R1) => R2,
  f1: (...args: TArgs) => R1
): (...args: TArgs) => R7;
compose<TArgs extends any[], R1, R2, R3, R4, R5, R6>(
  f6: (a: R5) => R6,
  f5: (a: R4) => R5,
  f4: (a: R3) => R4,
  f3: (a: R2) => R3,
  f2: (a: R1) => R2,
  f1: (...args: TArgs) => R1
): (...args: TArgs) => R6;
compose<TArgs extends any[], R1, R2, R3, R4, R5>(
  f5: (a: R4) => R5,
  f4: (a: R3) => R4,
  f3: (a: R2) => R3,
  f2: (a: R1) => R2,
  f1: (...args: TArgs) => R1
): (...args: TArgs) => R5;
compose<TArgs extends any[], R1, R2, R3, R4>(
  f4: (a: R3) => R4,
  f3: (a: R2) => R3,
  f2: (a: R1) => R2,
  f1: (...args: TArgs) => R1
): (...args: TArgs) => R4;
compose<TArgs extends any[], R1, R2, R3>(
  f3: (a: R2) => R3,
  f2: (a: R1) => R2,
  f1: (...args: TArgs) => R1
): (...args: TArgs) => R3;
compose<TArgs extends any[], R1, R2>(
  f2: (a: R1) => R2,
  f1: (...args: TArgs) => R1
): (...args: TArgs) => R2;
compose<TArgs extends any[], R1>(
  f1: (...args: TArgs) => R1
): (...args: TArgs) => R1;
R.compose source
import { pipe } from './pipe.js'

export function compose(){
  if (arguments.length === 0){
    throw new Error('compose requires at least one argument')
  }

  return pipe.apply(this, Array.prototype.slice.call(arguments, 0).reverse())
}
Tests
import { compose as composeRamda } from 'ramda'

import { add } from './add.js'
import { compose } from './compose.js'
import { filter } from './filter.js'
import { last } from './last.js'
import { map } from './map.js'

test('happy', () => {
  const result = compose(
    last, map(add(10)), map(add(1))
  )([ 1, 2, 3 ])

  expect(result).toBe(14)
})

test('can accepts initially two arguments', () => {
  const result = compose(map(x => x * 2),
    (list, limit) => filter(x => x > limit, list))([ 1, 2, 3, 4, false ], 2)

  expect(result).toEqual([ 6, 8 ])
})

test('when no arguments is passed', () => {
  expect(() => compose()).toThrowErrorMatchingInlineSnapshot('"compose requires at least one argument"')
})

test('ramda spec', () => {
  const f = function (
    a, b, c
  ){
    return [ a, b, c ]
  }
  const g = compose(f)

  expect(g(
    1, 2, 3
  )).toEqual([ 1, 2, 3 ])
})

test('does return correct length of composed function', () => {
  expect(compose(
    map, map, map
  )).toHaveLength(2)
  expect(composeRamda(
    map, map, map
  )).toHaveLength(2)
})

---------------

composeAsync

composeAsync<TArg, R1, R2, R3, R4, R5, R6, R7, TResult>(
  ...func: [
      fnLast: (a: any) => TResult,
      ...func: Array<(a: any) => any>,
      f7: (a: Awaited<R6>) => R7,
      f6: (a: Awaited<R5>) => R6,
      f5: (a: Awaited<R4>) => R5,
      f4: (a: Awaited<R3>) => R4,
      f3: (a: Awaited<R2>) => R3,
      f2: (a: Awaited<R1>) => R2,
      f1: (a: Awaited<TArg>) => R1
  ]
): (a: TArg | Promise<TArg>) => TResult

Asynchronous version of R.compose. awaits the result of each function before passing it to the next. Returns a Promise of the result.

const add = async x => {
  await R.delay(100)
  return x + 1
}
const multiply = async x => {
  await R.delay(100)
  return x * 2 
}

const result = await R.composeAsync(
  add,
  multiply
)(1)
// `result` resolves to `3`

Try this R.composeAsync example in Rambda REPL

All TypeScript definitions
composeAsync<TArg, R1, R2, R3, R4, R5, R6, R7, TResult>(
  ...func: [
      fnLast: (a: any) => TResult,
      ...func: Array<(a: any) => any>,
      f7: (a: Awaited<R6>) => R7,
      f6: (a: Awaited<R5>) => R6,
      f5: (a: Awaited<R4>) => R5,
      f4: (a: Awaited<R3>) => R4,
      f3: (a: Awaited<R2>) => R3,
      f2: (a: Awaited<R1>) => R2,
      f1: (a: Awaited<TArg>) => R1
  ]
): (a: TArg | Promise<TArg>) => TResult;
composeAsync<TArg, R1, R2, R3, R4, R5, R6, R7, TResult>(
  f7: (a: Awaited<R6>) => R7,
  f6: (a: Awaited<R5>) => R6,
  f5: (a: Awaited<R4>) => R5,
  f4: (a: Awaited<R3>) => R4,
  f3: (a: Awaited<R2>) => R3,
  f2: (a: Awaited<R1>) => R2,
  f1: (a: Awaited<TArg>) => R1
): (a: TArg | Promise<TArg>) => R7;
composeAsync<TArg, R1, R2, R3, R4, R5, R6, R7>(
  f7: (a: Awaited<R6>) => R7,
  f6: (a: Awaited<R5>) => R6,
  f5: (a: Awaited<R4>) => R5,
  f4: (a: Awaited<R3>) => R4,
  f3: (a: Awaited<R2>) => R3,
  f2: (a: Awaited<R1>) => R2,
  f1: (a: Awaited<TArg>) => R1
): (a: TArg | Promise<TArg>) => R7;
composeAsync<TArg, R1, R2, R3, R4, R5, R6>(
  f6: (a: Awaited<R5>) => R6,
  f5: (a: Awaited<R4>) => R5,
  f4: (a: Awaited<R3>) => R4,
  f3: (a: Awaited<R2>) => R3,
  f2: (a: Awaited<R1>) => R2,
  f1: (a: Awaited<TArg>) => R1
): (a: TArg | Promise<TArg>) => R6;
composeAsync<TArg, R1, R2, R3, R4, R5>(
  f5: (a: Awaited<R4>) => R5,
  f4: (a: Awaited<R3>) => R4,
  f3: (a: Awaited<R2>) => R3,
  f2: (a: Awaited<R1>) => R2,
  f1: (a: Awaited<TArg>) => R1
): (a: TArg | Promise<TArg>) => R5;
composeAsync<TArg, R1, R2, R3, R4>(
  f4: (a: Awaited<R3>) => R4,
  f3: (a: Awaited<R2>) => R3,
  f2: (a: Awaited<R1>) => R2,
  f1: (a: Awaited<TArg>) => R1
): (a: TArg | Promise<TArg>) => R4;
composeAsync<TArg, R1, R2, R3>(
  f3: (a: Awaited<R2>) => R3,
  f2: (a: Awaited<R1>) => R2,
  f1: (a: Awaited<TArg>) => R1
): (a: TArg | Promise<TArg>) => R3;
composeAsync<TArg, R1, R2>(
  f2: (a: Awaited<R1>) => R2,
  f1: (a: Awaited<TArg>) => R1
): (a: TArg | Promise<TArg>) => R2;
composeAsync<TArg, R1>(
  f1: (a: Awaited<TArg>) => R1
): (a: TArg | Promise<TArg>) => R1;
R.composeAsync source
import { pipeAsync } from './pipeAsync.js'

export function composeAsync(...fnList){
  return pipeAsync(...fnList.reverse())
}
Tests
import { composeAsync } from './composeAsync.js'
import { delay } from './delay.js'

async function identity(x){
  await delay(100)

  return x
}

test('happy', async () => {
  const fn1 = async x => {
    await delay(100)

    return x.map(xx => xx + 1)
  }
  const fn2 = async x => {
    await delay(100)

    return x.map(xx => xx * 2)
  }
  const result = await composeAsync(fn1,
    fn2)(await Promise.all([ identity(1), identity(2), identity(3) ]))

  expect(result).toEqual([ 3, 5, 7 ])
})

const delayFn = ms =>
  new Promise(resolve => {
    resolve(ms + 1)
  })

test('with function returning promise', async () => {
  const result = await composeAsync(
    x => x,
    x => x + 1,
    delayFn,
    x => x
  )(1)

  expect(result).toBe(3)
})

test('throw error', async () => {
  const fn = async () => {
    await delay(1)
    JSON.parse('{foo')
  }

  let didThrow = false
  try {
    await composeAsync(fn, x => x + 1)(20)
  } catch (e){
    didThrow = true
  }

  expect(didThrow).toBeTrue()
})

---------------

composeWith

composeWith<TArgs extends any[], TResult>(
  transformer: (fn: (...args: any[]) => any, intermediatResult: any) => any,
  fns: AtLeastOneFunctionsFlowFromRightToLeft<TArgs, TResult>,
): (...args: TArgs) => TResult
const result = R.composeWith(
  (fn, intermediateResult) => fn(intermediateResult),
  [
    R.map(x => x + 1),
    R.map(x => x * 2),
  ]
)([1, 2, 3])
// => [3, 5, 7]

Try this R.composeWith example in Rambda REPL

All TypeScript definitions
composeWith<TArgs extends any[], TResult>(
  transformer: (fn: (...args: any[]) => any, intermediatResult: any) => any,
  fns: AtLeastOneFunctionsFlowFromRightToLeft<TArgs, TResult>,
): (...args: TArgs) => TResult;
composeWith(
  transformer: (fn: (...args: any[]) => any, intermediatResult: any) => any,
): <TArgs extends any[], TResult>(
  fns: AtLeastOneFunctionsFlowFromRightToLeft<TArgs, TResult>,
) => (...args: TArgs) => TResult;
R.composeWith source
import { _arity } from './_internals/_arity.js'
import { head } from './head.js'
import { identity } from './identity.js'
import { reduce } from './reduce.js'
import { reverse } from './reverse.js'
import { tail } from './tail.js'

export function pipeWith(xf, list){
  if (list.length <= 0){
    return identity
  }

  const headList = head(list)
  const tailList = tail(list)

  return _arity(headList.length, function (){
    return reduce(
      function (result, f){
        return xf.call(
          this, f, result
        )
      },
      headList.apply(this, arguments),
      tailList
    )
  })
}

export function composeWith(xf, list){
  if (arguments.length === 1) return _list => composeWith(xf, _list)

  return pipeWith.apply(this, [ xf, reverse(list) ])
}
Tests
import { always, identity, inc, isNil, map, modulo, multiply } from 'rambdax'
import { composeWith as composeWithRamda, concat, flip, ifElse } from 'ramda'

import { composeWith } from './composeWith.js'

test('performs right-to-left function composition with function applying', () => {
  const f = composeWith((f, res) => f(res))([ map, multiply, parseInt ])

  expect(f).toHaveLength(2)
  expect(f('10')([ 1, 2, 3 ])).toEqual([ 10, 20, 30 ])
  expect(f('10', 2)([ 1, 2, 3 ])).toEqual([ 2, 4, 6 ])
})

test('performs right-to-left function while not nil result', () => {
  const isOdd = flip(modulo)(2)
  const composeWhenNotNil = composeWithRamda((f, res) =>
    isNil(res) ? null : f(res))

  const f = composeWhenNotNil([
    inc,
    ifElse(
      isOdd, identity, always(null)
    ),
    parseInt,
  ])
  expect(f).toHaveLength(2)
  expect(f('1')).toBe(2)
  expect(f('2')).toBeNull()
})

test('performs right-to-left function using promise chaining', () => {
  const then = function (f, p){
    return p.then(f)
  }
  const composeP = composeWithRamda(then)
  const toListPromise = function (a){
    return new Promise(res => {
      res([ a ])
    })
  }
  const doubleListPromise = function (a){
    return new Promise(res => {
      res(concat(a, a))
    })
  }
  const f = composeP([ doubleListPromise, toListPromise ])

  return f(1).then(res => {
    expect(res).toEqual([ 1, 1 ])
  })
})

---------------

concat

concat<T>(x: T[], y: T[]): T[]

It returns a new string or array, which is the result of merging x and y.

R.concat([1, 2])([3, 4]) // => [1, 2, 3, 4]
R.concat('foo', 'bar') // => 'foobar'

Try this R.concat example in Rambda REPL

All TypeScript definitions
concat<T>(x: T[], y: T[]): T[];
concat<T>(x: T[]): (y: T[]) => T[];
concat(x: string, y: string): string;
concat(x: string): (y: string) => string;
R.concat source
export function concat(x, y){
  if (arguments.length === 1) return _y => concat(x, _y)

  return typeof x === 'string' ? `${ x }${ y }` : [ ...x, ...y ]
}
Tests
import { concat } from './concat.js'

test('happy', () => {
  const arr1 = [ 'a', 'b', 'c' ]
  const arr2 = [ 'd', 'e', 'f' ]

  const a = concat(arr1, arr2)
  const b = concat(arr1)(arr2)
  const expectedResult = [ 'a', 'b', 'c', 'd', 'e', 'f' ]

  expect(a).toEqual(expectedResult)
  expect(b).toEqual(expectedResult)
})

test('with strings', () => {
  expect(concat('ABC', 'DEF')).toBe('ABCDEF')
})

---------------

cond

cond<T extends any[], R>(conditions: Array<CondPair<T, R>>): (...args: T) => R

It takes list with conditions and returns a new function fn that expects input as argument.

This function will start evaluating the conditions in order to find the first winner(order of conditions matter).

The winner is this condition, which left side returns true when input is its argument. Then the evaluation of the right side of the winner will be the final result.

If no winner is found, then fn returns undefined.

const fn = R.cond([
  [ x => x > 25, R.always('more than 25') ],
  [ x => x > 15, R.always('more than 15') ],
  [ R.T, x => `${x} is nothing special` ],
])

const result = [
  fn(30),
  fn(20),
  fn(10),
] 
// => ['more than 25', 'more than 15', '10 is nothing special']

Try this R.cond example in Rambda REPL

All TypeScript definitions
cond<T extends any[], R>(conditions: Array<CondPair<T, R>>): (...args: T) => R;
R.cond source
export function cond(conditions){
  return (...input) => {
    let done = false
    let toReturn
    conditions.forEach(([ predicate, getResult ]) => {
      if (!done && predicate(...input)){
        done = true
        toReturn = getResult(...input)
      }
    })

    return toReturn
  }
}
Tests
import { always } from './always.js'
import { cond } from './cond.js'
import { equals } from './equals.js'
import { T } from './T.js'

test('returns a function', () => {
  expect(typeof cond([])).toBe('function')
})

test('returns a conditional function', () => {
  const fn = cond([
    [ equals(0), always('water freezes at 0°C') ],
    [ equals(100), always('water boils at 100°C') ],
    [
      T,
      function (temp){
        return 'nothing special happens at ' + temp + '°C'
      },
    ],
  ])
  expect(fn(0)).toBe('water freezes at 0°C')
  expect(fn(50)).toBe('nothing special happens at 50°C')
  expect(fn(100)).toBe('water boils at 100°C')
})

test('no winner', () => {
  const fn = cond([
    [ equals('foo'), always(1) ],
    [ equals('bar'), always(2) ],
  ])
  expect(fn('quux')).toBeUndefined()
})

test('predicates are tested in order', () => {
  const fn = cond([
    [ T, always('foo') ],
    [ T, always('bar') ],
    [ T, always('baz') ],
  ])
  expect(fn()).toBe('foo')
})

test('pass all inputs',() => {
  cond([ [()=> true, (...x) => {
    expect(x).toEqual([1,2,3])
  }] ])(1,2,3)
})

---------------

contains

contains<T, U>(target: T, compareTo: U): boolean

It returns true if all of target object properties are R.equal to compareTo object.

const result = R.contains({a:1}, {a:1, b:2})
// => true

Try this R.contains example in Rambda REPL

All TypeScript definitions
contains<T, U>(target: T, compareTo: U): boolean;
contains<T, U>(target: T): (compareTo: U) => boolean;
R.contains source
import { equals } from './equals.js'

export function contains(target, toCompare){
  if (arguments.length === 1){
    return _toCompare => contains(target, _toCompare)
  }
  let willReturn = true

  Object.keys(target).forEach(prop => {
    if (!willReturn) return
    if (
      toCompare[ prop ] === undefined ||
      !equals(target[ prop ], toCompare[ prop ])
    ){
      willReturn = false
    }
  })

  return willReturn
}
Tests
import { contains } from './contains.js'

const target = { a : 1 }
const compareTo = {
  a : 1,
  b : 2,
}

test('happy', () => {
  expect(contains(target, compareTo)).toBeTrue()
})

test('curried', () => {
  expect(contains({
    ...target,
    c : 3,
  },
  compareTo)).toBeFalse()
})

---------------

converge

converge(after: ((...a: any[]) => any), fns: ((...x: any[]) => any)[]): (...y: any[]) => any

Accepts a converging function and a list of branching functions and returns a new function. When invoked, this new function is applied to some arguments, each branching function is applied to those same arguments. The results of each branching function are passed as arguments to the converging function to produce the return value.

💥 Explanation is taken from Ramda documentation

const result = R.converge(R.multiply)([ R.add(1), R.add(3) ])(2)
// => 15

Try this R.converge example in Rambda REPL

All TypeScript definitions
converge(after: ((...a: any[]) => any), fns: ((...x: any[]) => any)[]): (...y: any[]) => any;
R.converge source
import { curryN } from './curryN.js'
import { map } from './map.js'
import { max } from './max.js'
import { reduce } from './reduce.js'

export function converge(fn, transformers){
  if (arguments.length === 1)
    return _transformers => converge(fn, _transformers)

  const highestArity = reduce(
    (a, b) => max(a, b.length), 0, transformers
  )

  return curryN(highestArity, function (){
    return fn.apply(this,
      map(g => g.apply(this, arguments), transformers))
  })
}
Tests
import { add } from './add.js'
import { converge } from './converge.js'
import { multiply } from './multiply.js'

const f1 = converge(multiply, [ a => a + 1, a => a + 10 ])
const f2 = converge(multiply, [ a => a + 1, (a, b) => a + b + 10 ])
const f3 = converge(multiply, [ a => a + 1, (
  a, b, c
) => a + b + c + 10 ])

test('happy', () => {
  expect(f2(6, 7)).toBe(161)
})

test('passes the results of applying the arguments individually', () => {
  const result = converge(multiply)([ add(1), add(3) ])(2)
  expect(result).toBe(15)
})

test('returns a function with the length of the longest argument', () => {
  expect(f1).toHaveLength(1)
  expect(f2).toHaveLength(2)
  expect(f3).toHaveLength(3)
})

test('passes context to its functions', () => {
  const a = function (x){
    return this.f1(x)
  }
  const b = function (x){
    return this.f2(x)
  }
  const c = function (x, y){
    return this.f3(x, y)
  }
  const d = converge(c, [ a, b ])
  const context = {
    f1 : add(1),
    f2 : add(2),
    f3 : add,
  }
  expect(a.call(context, 1)).toBe(2)
  expect(b.call(context, 1)).toBe(3)
  expect(d.call(context, 1)).toBe(5)
})

test('works with empty functions list', () => {
  const fn = converge(function (){
    return arguments.length
  }, [])
  expect(fn).toHaveLength(0)
  expect(fn()).toBe(0)
})

---------------

count

count<T>(predicate: (x: T) => boolean, list: T[]): number

It counts how many times predicate function returns true, when supplied with iteration of list.

const list = [{a: 1}, 1, {a:2}]
const result = R.count(x => x.a !== undefined, list)
// => 2

Try this R.count example in Rambda REPL

All TypeScript definitions
count<T>(predicate: (x: T) => boolean, list: T[]): number;
count<T>(predicate: (x: T) => boolean): (list: T[]) => number;
R.count source
import { isArray } from './_internals/isArray.js'

export function count(predicate, list){
  if (arguments.length === 1){
    return _list => count(predicate, _list)
  }
  if (!isArray(list)) return 0

  return list.filter(x => predicate(x)).length
}
Tests
import { count as countRamda } from 'ramda'

import { count } from './count.js'

const predicate = x => x.a !== undefined

test('with empty list', () => {
  expect(count(predicate, [])).toBe(0)
})

test('happy', () => {
  const list = [ 1, 2, { a : 1 }, 3, { a : 1 } ]

  expect(count(predicate)(list)).toBe(2)
})

test('rambdax/issues/86', () => {
  const arr = [ true, false, true, false ]
  expect(count(Boolean, arr)).toBe(countRamda(Boolean, arr))
})

---------------

countBy

countBy<T extends unknown>(transformFn: (x: T) => any, list: T[]): Record<string, number>

It counts elements in a list after each instance of the input list is passed through transformFn function.

const list = [ 'a', 'A', 'b', 'B', 'c', 'C' ]

const result = countBy(R.toLower, list)
const expected = { a: 2, b: 2, c: 2 }
// => `result` is equal to `expected`

Try this R.countBy example in Rambda REPL

All TypeScript definitions
countBy<T extends unknown>(transformFn: (x: T) => any, list: T[]): Record<string, number>;
countBy<T extends unknown>(transformFn: (x: T) => any): (list: T[]) => Record<string, number>;
R.countBy source
export function countBy(fn, list){
  if (arguments.length === 1){
    return _list => countBy(fn, _list)
  }
  const willReturn = {}

  list.forEach(item => {
    const key = fn(item)
    if (!willReturn[ key ]){
      willReturn[ key ] = 1
    } else {
      willReturn[ key ]++
    }
  })

  return willReturn
}
Tests
import { countBy } from './countBy.js'

const list = [ 'a', 'A', 'b', 'B', 'c', 'C' ]

test('happy', () => {
  const result = countBy(x => x.toLowerCase(), list)
  expect(result).toEqual({
    a : 2,
    b : 2,
    c : 2,
  })
})

---------------

curry

curry(fn: AnyFunction): (...a: any[]) => any

It expects a function as input and returns its curried version.

const fn = (a, b, c) => a + b + c
const curried = R.curry(fn)
const sum = curried(1,2)

const result = sum(3) // => 6

Try this R.curry example in Rambda REPL

All TypeScript definitions
curry(fn: AnyFunction): (...a: any[]) => any;
R.curry source
export function curry(fn, args = []){
  return (..._args) =>
    (rest => rest.length >= fn.length ? fn(...rest) : curry(fn, rest))([
      ...args,
      ..._args,
    ])
}
Tests
import { curry } from './curry.js'

test('happy', () => {
  const addFourNumbers = (
    a, b, c, d
  ) => a + b + c + d
  const curriedAddFourNumbers = curry(addFourNumbers)
  const f = curriedAddFourNumbers(1, 2)
  const g = f(3)

  expect(g(4)).toBe(10)
})

test('when called with more arguments', () => {
  const add = curry((n, n2) => n + n2)

  expect(add(
    1, 2, 3
  )).toBe(3)
})

test('when called with zero arguments', () => {
  const sub = curry((a, b) => a - b)
  const s0 = sub()

  expect(s0(5, 2)).toBe(3)
})

test('when called via multiple curry stages', () => {
  const join = curry((
    a, b, c, d
  ) => [ a, b, c, d ].join('-'))

  const stage1 = join('A')
  const stage2 = stage1('B', 'C')

  expect(stage2('D')).toBe('A-B-C-D')
})

---------------

curryN

curryN(length: number, fn: AnyFunction): (...a: any[]) => any

It returns a curried equivalent of the provided function, with the specified arity.

All TypeScript definitions
curryN(length: number, fn: AnyFunction): (...a: any[]) => any;
R.curryN source
import { _arity } from './_internals/_arity.js'

function _curryN(
  n, cache, fn
){
  return function (){
    let ci = 0
    let ai = 0
    const cl = cache.length
    const al = arguments.length
    const args = new Array(cl + al)
    while (ci < cl){
      args[ ci ] = cache[ ci ]
      ci++
    }
    while (ai < al){
      args[ cl + ai ] = arguments[ ai ]
      ai++
    }
    const remaining = n - args.length

    return args.length >= n ?
      fn.apply(this, args) :
      _arity(remaining, _curryN(
        n, args, fn
      ))
  }
}

export function curryN(n, fn){
  if (arguments.length === 1) return _fn => curryN(n, _fn)

  if (n > 10){
    throw new Error('First argument to _arity must be a non-negative integer no greater than ten')
  }

  return _arity(n, _curryN(
    n, [], fn
  ))
}
Tests
import { curryN } from './curryN.js'

function multiply(
  a, b, c, d, e, f, g, h, i, j, k, l
){
  if (l){
    return a * b * c * d * e * f * g * h * i * j * k * l
  }
  if (k){
    return a * b * c * d * e * f * g * h * i * j * k
  }
  if (j){
    return a * b * c * d * e * f * g * h * i * j
  }
  if (i){
    return a * b * c * d * e * f * g * h * i
  }
  if (h){
    return a * b * c * d * e * f * g * h
  }
  if (g){
    return a * b * c * d * e * f * g
  }
  if (f){
    return a * b * c * d * e * f
  }
  if (e){
    return a * b * c * d * e
  }

  return a * b * c
}

test('accepts an arity', () => {
  const curried = curryN(3, multiply)
  expect(curried(1)(2)(3)).toBe(6)
  expect(curried(1, 2)(3)).toBe(6)
  expect(curried(1)(2, 3)).toBe(6)
  expect(curried(
    1, 2, 3
  )).toBe(6)
})

test('can be partially applied', () => {
  const curry3 = curryN(3)
  const curried = curry3(multiply)
  expect(curried).toHaveLength(3)
  expect(curried(1)(2)(3)).toBe(6)
  expect(curried(1, 2)(3)).toBe(6)
  expect(curried(1)(2, 3)).toBe(6)
  expect(curried(
    1, 2, 3
  )).toBe(6)
})

test('preserves context', () => {
  const ctx = { x : 10 }
  const f = function (a, b){
    return a + b * this.x
  }
  const g = curryN(2, f)

  expect(g.call(
    ctx, 2, 4
  )).toBe(42)
  expect(g.call(ctx, 2).call(ctx, 4)).toBe(42)
})

test('number of arguments is 4', () => {
  const fn = curryN(4, multiply)
  expect(fn(
    1, 2, 3, 4
  )).toBe(6)
})

test('number of arguments is 5', () => {
  const fn = curryN(5, multiply)
  expect(fn(
    1, 2, 3, 4, 5
  )).toBe(120)
})

test('number of arguments is 6', () => {
  const fn = curryN(6, multiply)
  expect(fn(
    1, 2, 3, 4, 5, 6
  )).toBe(720)
})

test('number of arguments is 7', () => {
  const fn = curryN(7, multiply)
  expect(fn(
    1, 2, 3, 4, 5, 6, 7
  )).toBe(5040)
})

test('number of arguments is 8', () => {
  const fn = curryN(8, multiply)
  expect(fn(
    1, 2, 3, 4, 5, 6, 7, 8
  )).toBe(40320)
})

test('number of arguments is 9', () => {
  const fn = curryN(9, multiply)
  expect(fn(
    1, 2, 3, 4, 5, 6, 7, 8, 9
  )).toBe(362880)
})

test('number of arguments is 10', () => {
  const fn = curryN(10, multiply)
  expect(fn(
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10
  )).toBe(3628800)
})

test('number of arguments is 11', () => {
  expect(() => {
    const fn = curryN(11, multiply)
    fn(
      1, 2, 3, 4, 5, 6, 7, 8, 9, 10
    )
  }).toThrowWithMessage(Error,
    'First argument to _arity must be a non-negative integer no greater than ten')
})

test('forwards extra arguments', () => {
  const createArray = function (){
    return Array.prototype.slice.call(arguments)
  }
  const fn = curryN(3, createArray)

  expect(fn(
    1, 2, 3
  )).toEqual([ 1, 2, 3 ])
  expect(fn(
    1, 2, 3, 4
  )).toEqual([ 1, 2, 3, 4 ])
  expect(fn(1, 2)(3, 4)).toEqual([ 1, 2, 3, 4 ])
  expect(fn(1)(
    2, 3, 4
  )).toEqual([ 1, 2, 3, 4 ])
  expect(fn(1)(2)(3, 4)).toEqual([ 1, 2, 3, 4 ])
})

---------------

debounce

debounce<T, U>(fn: (input: T) => U, ms: number, immediate?: boolean): (input: T) => void
let counter = 0
const increment = () => {
  counter++
}

const debounced = R.debounce(increment, 1000)

async function fn(){
  debounced()
  await R.delay(500)
  debounced()
  await R.delay(800)
  console.log(counter) // => 0

  await R.delay(1200)
  console.log(counter) // => 1

  return counter
}
const result = await fn()
// `result` resolves to `1`

Try this R.debounce example in Rambda REPL

All TypeScript definitions
debounce<T, U>(fn: (input: T) => U, ms: number, immediate?: boolean): (input: T) => void;
debounce<T, Q, U>(fn: (input1: T, input2: Q) => U, ms: number, immediate?: boolean): (input1: T, input2: Q) => void;
debounce<T, Q, Z, U>(fn: (input1: T, input2: Q, input3: Z) => U, ms: number, immediate?: boolean): (input1: T, input2: Q, input3: Z) => void;
R.debounce source
export function debounce(
  func, ms, immediate = false
){
  let timeout

  return function (...input){
    const later = function (){
      timeout = null
      if (!immediate){
        return func.apply(null, input)
      }
    }
    const callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, ms)
    if (callNow){
      return func.apply(null, input)
    }
  }
}
Tests
import { debounce } from './debounce.js'
import { delay } from './delay.js'

test('happy', async () => {
  let counter = 0
  let aHolder

  const inc = a => {
    aHolder = a
    counter++
  }
  const incWrapped = debounce(inc, 500)

  incWrapped(1)
  expect(counter).toBe(0)

  await delay(200)

  incWrapped(2)
  expect(counter).toBe(0)

  await delay(700)
  expect(counter).toBe(1)
  expect(aHolder).toBe(2)
})

test('immediate debounce', async () => {
  let counter = 0
  const inc = () => {
    counter++
  }

  const incWrapped = debounce(
    inc, 500, true
  )
  incWrapped()
  expect(counter).toBe(1)
  await delay(200)
  incWrapped()
  expect(counter).toBe(1)
  await delay(700)
  incWrapped()
  expect(counter).toBe(2)
})

---------------

dec

dec(x: number): number

It decrements a number.

const result = R.dec(2) // => 1

Try this R.dec example in Rambda REPL

All TypeScript definitions
dec(x: number): number;
R.dec source
export const dec = x => x - 1
Tests
import { dec } from './dec.js'

test('happy', () => {
  expect(dec(2)).toBe(1)
})

---------------

defaultTo

defaultTo<T>(defaultValue: T, input: T | null | undefined): T

It returns defaultValue, if all of inputArguments are undefined, null or NaN.

Else, it returns the first truthy inputArguments instance(from left to right).

💥 Rambda's defaultTo accept indefinite number of arguments when non curried, i.e. R.defaultTo(2, foo, bar, baz).

R.defaultTo('foo', 'bar') // => 'bar'
R.defaultTo('foo', undefined) // => 'foo'

// Important - emtpy string is not falsy value(same as Ramda)
R.defaultTo('foo', '') // => 'foo'

Try this R.defaultTo example in Rambda REPL

All TypeScript definitions
defaultTo<T>(defaultValue: T, input: T | null | undefined): T;
defaultTo<T>(defaultValue: T): (input: T | null | undefined) => T;
R.defaultTo source
function isFalsy(input){
  return (
    input === undefined || input === null || Number.isNaN(input) === true
  )
}

export function defaultTo(defaultArgument, input){
  if (arguments.length === 1){
    return _input => defaultTo(defaultArgument, _input)
  }

  return isFalsy(input) ? defaultArgument : input
}
Tests
import { defaultTo } from './defaultTo.js'

test('with undefined', () => {
  expect(defaultTo('foo')(undefined)).toBe('foo')
})

test('with null', () => {
  expect(defaultTo('foo')(null)).toBe('foo')
})

test('with NaN', () => {
  expect(defaultTo('foo')(NaN)).toBe('foo')
})

test('with empty string', () => {
  expect(defaultTo('foo', '')).toBe('')
})

test('with false', () => {
  expect(defaultTo('foo', false)).toBeFalse()
})

test('when inputArgument passes initial check', () => {
  expect(defaultTo('foo', 'bar')).toBe('bar')
})

---------------

delay

delay(ms: number): Promise<'RAMBDAX_DELAY'>

setTimeout as a promise that resolves to R.DELAY variable after ms milliseconds.

const result = R.delay(1000)
// `result` resolves to `RAMBDAX_DELAY`

Try this R.delay example in Rambda REPL

All TypeScript definitions
delay(ms: number): Promise<'RAMBDAX_DELAY'>;
R.delay source
export const DELAY = 'RAMBDAX_DELAY'

export function delay(ms){
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(DELAY)
    }, ms)
  })
}
Tests
import { DELAY, delay } from './delay.js'

test('usage with variables', async () => {
  await expect(delay(500)).resolves.toBe(DELAY)
})

---------------

descend

descend<T>(fn: (obj: T) => Ord, a: T, b: T): Ordering
const result = R.sort(R.descend(x => x), [1, 2])
// => [2, 1]

Try this R.descend example in Rambda REPL

All TypeScript definitions
descend<T>(fn: (obj: T) => Ord, a: T, b: T): Ordering;
descend<T>(fn: (obj: T) => Ord): (a: T, b: T) => Ordering;
R.descend source
import { createCompareFunction } from './ascend.js'

export function descend(
  getFunction, a, b
){
  if (arguments.length === 1){
    return (_a, _b) => descend(
      getFunction, _a, _b
    )
  }
  const aValue = getFunction(a)
  const bValue = getFunction(b)

  return createCompareFunction(
    aValue, bValue, 1, -1
  )
}

---------------

difference

difference<T>(a: T[], b: T[]): T[]

It returns the uniq set of all elements in the first list a not contained in the second list b.

R.equals is used to determine equality.

const a = [ 1, 2, 3, 4 ]
const b = [ 3, 4, 5, 6 ]

const result = R.difference(a, b)
// => [ 1, 2 ]

Try this R.difference example in Rambda REPL

All TypeScript definitions
difference<T>(a: T[], b: T[]): T[];
difference<T>(a: T[]): (b: T[]) => T[];
R.difference source
import { includes } from './includes.js'
import { uniq } from './uniq.js'

export function difference(a, b){
  if (arguments.length === 1) return _b => difference(a, _b)

  return uniq(a).filter(aInstance => !includes(aInstance, b))
}
Tests
import { difference as differenceRamda } from 'ramda'

import { difference } from './difference.js'

test('difference', () => {
  const a = [ 1, 2, 3, 4 ]
  const b = [ 3, 4, 5, 6 ]
  expect(difference(a)(b)).toEqual([ 1, 2 ])

  expect(difference([], [])).toEqual([])
})

test('difference with objects', () => {
  const a = [ { id : 1 }, { id : 2 }, { id : 3 }, { id : 4 } ]
  const b = [ { id : 3 }, { id : 4 }, { id : 5 }, { id : 6 } ]
  expect(difference(a, b)).toEqual([ { id : 1 }, { id : 2 } ])
})

test('no duplicates in first list', () => {
  const M2 = [ 1, 2, 3, 4, 1, 2, 3, 4 ]
  const N2 = [ 3, 3, 4, 4, 5, 5, 6, 6 ]
  expect(difference(M2, N2)).toEqual([ 1, 2 ])
})

test('should use R.equals', () => {
  expect(difference([ 1 ], [ 1 ])).toHaveLength(0)
  expect(differenceRamda([ NaN ], [ NaN ])).toHaveLength(0)
})

---------------

differenceWith

differenceWith<T1, T2>(
  pred: (a: T1, b: T2) => boolean,
  list1: T1[],
  list2: T2[],
): T1[]
const result = R.differenceWith(
  (a, b) => a.x === b.x,
  [{x: 1}, {x: 2}],
  [{x: 1}, {x: 3}]
)
// => [{x: 2}]

Try this R.differenceWith example in Rambda REPL

All TypeScript definitions
differenceWith<T1, T2>(
  pred: (a: T1, b: T2) => boolean,
  list1: T1[],
  list2: T2[],
): T1[];
differenceWith<T1, T2>(
  pred: (a: T1, b: T2) => boolean,
): (list1: T1[], list2: T2[]) => T1[];
differenceWith<T1, T2>(
  pred: (a: T1, b: T2) => boolean,
  list1: T1[],
): (list2: T2[]) => T1[];
R.differenceWith source
import { curry } from './curry.js'
import { _indexOf } from './equals.js'

export function differenceWithFn(
  fn, a, b
){
  const willReturn = []
  const [ first, second ] = a.length >= b.length ? [ a, b ] : [ b, a ]

  first.forEach(item => {
    const hasItem = second.some(secondItem => fn(item, secondItem))
    if (!hasItem && _indexOf(item, willReturn) === -1){
      willReturn.push(item)
    }
  })

  return willReturn
}

export const differenceWith = curry(differenceWithFn)
Tests
import { differenceWith } from './differenceWith.js';

const fn = (a, b) => a.x === b.x;

test('same length of list', () => {
	const result = differenceWith(fn, [{ x: 1 }, { x: 2 }], [{ x: 1 }, { x: 3 }]);
	expect(result).toEqual([{ x: 2 }]);
});

test('different length of list', () => {
	const foo = [{ x: 1 }, { x: 2 }, { x: 3 }];
	const bar = [{ x: 3 }, { x: 4 }];
	const result = differenceWith(fn, foo, bar);
	expect(result).toEqual([{ x: 1 }, { x: 2 }]);
});

---------------

dissoc

dissoc<K extends PropertyKey>(prop: K): <U extends { [P in K]?: any}>(obj: string extends keyof U ? U : undefined extends U[K] ? U : never) => U

It returns a new object that does not contain property prop.

R.dissoc('b', {a: 1, b: 2, c: 3})
// => {a: 1, c: 3}

Try this R.dissoc example in Rambda REPL

All TypeScript definitions
dissoc<K extends PropertyKey>(prop: K): <U extends { [P in K]?: any}>(obj: string extends keyof U ? U : undefined extends U[K] ? U : never) => U;
dissoc<U, K extends keyof U>(prop: string extends keyof U ? K : undefined extends U[K] ? K : never, obj: U): U;
R.dissoc source
export function dissoc(prop, obj){
  if (arguments.length === 1) return _obj => dissoc(prop, _obj)

  if (obj === null || obj === undefined) return {}

  const willReturn = {}
  for (const p in obj){
    willReturn[ p ] = obj[ p ]
  }
  delete willReturn[ prop ]

  return willReturn
}
Tests
import { dissoc } from './dissoc.js'

test('input is null or undefined', () => {
  expect(dissoc('b', null)).toEqual({})
  expect(dissoc('b', undefined)).toEqual({})
})

test('property exists curried', () => {
  expect(dissoc('b')({
    a : 1,
    b : 2,
  })).toEqual({ a : 1 })
})

test('property doesn\'t exists', () => {
  expect(dissoc('c', {
    a : 1,
    b : 2,
  })).toEqual({
    a : 1,
    b : 2,
  })
})

test('works with non-string property', () => {
  expect(dissoc(42, {
    a  : 1,
    42 : 2,
  })).toEqual({ a : 1 })

  expect(dissoc(null, {
    a    : 1,
    null : 2,
  })).toEqual({ a : 1 })

  expect(dissoc(undefined, {
    a         : 1,
    undefined : 2,
  })).toEqual({ a : 1 })
})

test('includes prototype properties', () => {
  function Rectangle(width, height){
    this.width = width
    this.height = height
  }
  const area = Rectangle.prototype.area = function (){
    return this.width * this.height
  }
  const rect = new Rectangle(7, 6)

  expect(dissoc('area', rect)).toEqual({
    width  : 7,
    height : 6,
  })

  expect(dissoc('width', rect)).toEqual({
    height : 6,
    area,
  })

  expect(dissoc('depth', rect)).toEqual({
    width  : 7,
    height : 6,
    area,
  })
})

---------------

dissocPath

dissocPath<T>(path: Path, obj: any): T
const result = R.dissocPath(['a', 'b'], {a: {b: 1, c: 2}})
// => {a: {c: 2}}

Try this R.dissocPath example in Rambda REPL

All TypeScript definitions
dissocPath<T>(path: Path, obj: any): T;
dissocPath<T>(path: Path): (obj: any) => T;
R.dissocPath source
import { createPath } from '../src/_internals/createPath.js'
import { isArray } from './_internals/isArray.js'
import { isIndexInteger } from './_internals/isInteger.js'
import { omit } from './omit.js'
import { path } from './path.js'
import { removeIndex } from './removeIndex.js'
import { update } from './update.js'

export function dissocPath(pathInput, input){
  if (arguments.length === 1) return _obj => dissocPath(pathInput, _obj)

  const pathArrValue = createPath(pathInput)
  // this {...input} spread could be done to satisfy ramda specs, but this is done on so many places
  // TODO: add warning that Rambda simply returns input if path is empty
  if (pathArrValue.length === 0) return input

  const pathResult = path(pathArrValue, input)
  if (pathResult === undefined) return input

  const index = pathArrValue[ 0 ]
  const condition =
    typeof input !== 'object' ||
    input === null ||
    !input.hasOwnProperty(index)
  if (pathArrValue.length > 1){
    const nextInput = condition ?
      isIndexInteger(pathArrValue[ 1 ]) ?
        [] :
        {} :
      input[ index ]
    const nextPathInput = Array.prototype.slice.call(pathArrValue, 1)
    const intermediateResult = dissocPath(
      nextPathInput, nextInput, input
    )
    if (isArray(input)) return update(
      index, intermediateResult, input
    )

    return {
      ...input,
      [ index ] : intermediateResult,
    }
  }
  if (isArray(input)) return removeIndex(index, input)

  return omit([ index ], input)
}
Tests
const assert = require('assert')
import { eq } from './_internals/testUtils.js'
import { dissocPath } from './dissocPath.js'

const testInput = {
  a : {
    b : 1,
    c : 2,
    d : { e : 3 },
  },
  f : [
    { g : 4 },
    {
      h : 5,
      i : 6,
      j : {
        k : 7,
        l : 8,
      },
    },
  ],
  m : 9,
}

test('update array', () => {
  const expected = {
    a : {
      b : 1,
      c : 2,
      d : { e : 3 },
    },
    f : [
      { g : 4 },
      {
        h : 5,
        j : {
          k : 7,
          l : 8,
        },
      },
    ],
    m : 9,
  }
  const result = dissocPath('f.1.i', testInput)
  expect(result).toEqual(expected)
})

test('update object', () => {
  const result = dissocPath('a.b', testInput)
  const expected = {
    a : {
      c : 2,
      d : { e : 3 },
    },
    f : [
      { g : 4 },
      {
        h : 5,
        i : 6,
        j : {
          k : 7,
          l : 8,
        },
      },
    ],
    m : 9,
  }
  expect(result).toEqual(expected)
})

test('does not try to omit inner properties that do not exist', () => {
  const obj1 = {
    a : 1,
    b : {
      c : 2,
      d : 3,
    },
    e : 4,
    f : 5,
  }
  const obj2 = dissocPath([ 'x', 0, 'z' ], obj1)
  eq(obj2, {
    a : 1,
    b : {
      c : 2,
      d : 3,
    },
    e : 4,
    f : 5,
  })
  // Note: reference equality below!
  assert.strictEqual(obj2.a, obj1.a)
  assert.strictEqual(obj2.b, obj1.b)
  assert.strictEqual(obj2.f, obj1.f)
})

test('leaves an empty object when all properties omitted', () => {
  const obj1 = {
    a : 1,
    b : { c : 2 },
    d : 3,
  }
  const obj2 = dissocPath([ 'b', 'c' ], obj1)
  eq(obj2, {
    a : 1,
    b : {},
    d : 3,
  })
})

test('leaves an empty array when all indexes are omitted', () => {
  const obj1 = {
    a : 1,
    b : [ 2 ],
    d : 3,
  }
  const obj2 = dissocPath([ 'b', 0 ], obj1)
  eq(obj2, {
    a : 1,
    b : [],
    d : 3,
  })
})

test('accepts empty path', () => {
  eq(dissocPath([], {
    a : 1,
    b : 2,
  }),
  {
    a : 1,
    b : 2,
  })
})

test('allow integer to be used as key for object', () => {
  eq(dissocPath([ 42 ], {
    42 : 3,
    a  : 1,
    b  : 2,
  }),
  {
    a : 1,
    b : 2,
  })
})

test('support remove null/undefined value path', () => {
  eq(dissocPath([ 'c', 'd' ], {
    a : 1,
    b : 2,
    c : null,
  }),
  {
    a : 1,
    b : 2,
    c : null,
  })
  eq(dissocPath([ 'c', 'd' ], {
    a : 1,
    b : 2,
    c : undefined,
  }),
  {
    a : 1,
    b : 2,
    c : undefined,
  })

  const obj1 = {
    a : 1,
    b : 2,
  }
  const obj2 = dissocPath([ 'c', 'd' ], obj1)

  eq(obj2, obj1)

  // NOTE: commented out on purpose
  // assert.notStrictEqual(obj2, obj1)
})

---------------

divide

divide(x: number, y: number): number
R.divide(71, 100) // => 0.71

Try this R.divide example in Rambda REPL

All TypeScript definitions
divide(x: number, y: number): number;
divide(x: number): (y: number) => number;
R.divide source
export function divide(a, b){
  if (arguments.length === 1) return _b => divide(a, _b)

  return a / b
}
Tests
import { divide } from './divide.js'

test('happy', () => {
  expect(divide(71, 100)).toBe(0.71)
  expect(divide(71)(100)).toBe(0.71)
})

---------------

drop

drop<T>(howMany: number, input: T[]): T[]

It returns howMany items dropped from beginning of list or string input.

R.drop(2, ['foo', 'bar', 'baz']) // => ['baz']
R.drop(2, 'foobar')  // => 'obar'

Try this R.drop example in Rambda REPL

All TypeScript definitions
drop<T>(howMany: number, input: T[]): T[];
drop(howMany: number, input: string): string;
drop<T>(howMany: number): {
  <T>(input: T[]): T[];
  (input: string): string;
};
R.drop source
export function drop(howManyToDrop, listOrString){
  if (arguments.length === 1) return _list => drop(howManyToDrop, _list)

  return listOrString.slice(howManyToDrop > 0 ? howManyToDrop : 0)
}
Tests
import assert from 'assert'

import { drop } from './drop.js'

test('with array', () => {
  expect(drop(2)([ 'foo', 'bar', 'baz' ])).toEqual([ 'baz' ])
  expect(drop(3, [ 'foo', 'bar', 'baz' ])).toEqual([])
  expect(drop(4, [ 'foo', 'bar', 'baz' ])).toEqual([])
})

test('with string', () => {
  expect(drop(3, 'rambda')).toBe('bda')
})

test('with non-positive count', () => {
  expect(drop(0, [ 1, 2, 3 ])).toEqual([ 1, 2, 3 ])
  expect(drop(-1, [ 1, 2, 3 ])).toEqual([ 1, 2, 3 ])
  expect(drop(-Infinity, [ 1, 2, 3 ])).toEqual([ 1, 2, 3 ])
})

test('should return copy', () => {
  const xs = [ 1, 2, 3 ]

  assert.notStrictEqual(drop(0, xs), xs)
  assert.notStrictEqual(drop(-1, xs), xs)
})

---------------

dropLast

dropLast<T>(howMany: number, input: T[]): T[]

It returns howMany items dropped from the end of list or string input.

R.dropLast(2, ['foo', 'bar', 'baz']) // => ['foo']
R.dropLast(2, 'foobar')  // => 'foob'

Try this R.dropLast example in Rambda REPL

All TypeScript definitions
dropLast<T>(howMany: number, input: T[]): T[];
dropLast(howMany: number, input: string): string;
dropLast<T>(howMany: number): {
  <T>(input: T[]): T[];
  (input: string): string;
};
R.dropLast source
export function dropLast(howManyToDrop, listOrString){
  if (arguments.length === 1){
    return _listOrString => dropLast(howManyToDrop, _listOrString)
  }

  return howManyToDrop > 0 ?
    listOrString.slice(0, -howManyToDrop) :
    listOrString.slice()
}
Tests
import assert from 'assert'

import { dropLast } from './dropLast.js'

test('with array', () => {
  expect(dropLast(2)([ 'foo', 'bar', 'baz' ])).toEqual([ 'foo' ])
  expect(dropLast(3, [ 'foo', 'bar', 'baz' ])).toEqual([])
  expect(dropLast(4, [ 'foo', 'bar', 'baz' ])).toEqual([])
})

test('with string', () => {
  expect(dropLast(3, 'rambda')).toBe('ram')
})

test('with non-positive count', () => {
  expect(dropLast(0, [ 1, 2, 3 ])).toEqual([ 1, 2, 3 ])
  expect(dropLast(-1, [ 1, 2, 3 ])).toEqual([ 1, 2, 3 ])
  expect(dropLast(-Infinity, [ 1, 2, 3 ])).toEqual([ 1, 2, 3 ])
})

test('should return copy', () => {
  const xs = [ 1, 2, 3 ]

  assert.notStrictEqual(dropLast(0, xs), xs)
  assert.notStrictEqual(dropLast(-1, xs), xs)
})

---------------

dropLastWhile

dropLastWhile(predicate: (x: string) => boolean, iterable: string): string
const list = [1, 2, 3, 4, 5];
const predicate = x => x >= 3

const result = dropLastWhile(predicate, list);
// => [1, 2]

Try this R.dropLastWhile example in Rambda REPL

All TypeScript definitions
dropLastWhile(predicate: (x: string) => boolean, iterable: string): string;
dropLastWhile(predicate: (x: string) => boolean): (iterable: string) => string;
dropLastWhile<T>(predicate: (x: T) => boolean, iterable: T[]): T[];
dropLastWhile<T>(predicate: (x: T) => boolean): <T>(iterable: T[]) => T[];
R.dropLastWhile source
import { isArray as isArrayMethod } from './_internals/isArray.js'

export function dropLastWhile(predicate, iterable){
  if (arguments.length === 1){
    return _iterable => dropLastWhile(predicate, _iterable)
  }
  if (iterable.length === 0) return iterable
  const isArray = isArrayMethod(iterable)

  if (typeof predicate !== 'function'){
    throw new Error(`'predicate' is from wrong type ${ typeof predicate }`)
  }
  if (!isArray && typeof iterable !== 'string'){
    throw new Error(`'iterable' is from wrong type ${ typeof iterable }`)
  }

  const toReturn = []
  let counter = iterable.length

  while (counter){
    const item = iterable[ --counter ]
    if (!predicate(item)){
      toReturn.push(item)
      break
    }
  }

  while (counter){
    toReturn.push(iterable[ --counter ])
  }

  return isArray ? toReturn.reverse() : toReturn.reverse().join('')
}
Tests
import { dropLastWhile as dropLastWhileRamda } from 'ramda'

import { compareCombinations } from './_internals/testUtils.js'
import { dropLastWhile } from './dropLastWhile.js'

const list = [ 1, 2, 3, 4, 5 ]
const str = 'foobar'

test('with list', () => {
  const result = dropLastWhile(x => x >= 3, list)
  expect(result).toEqual([ 1, 2 ])
})

test('with string', () => {
  const result = dropLastWhile(x => x !== 'b')(str)
  expect(result).toBe('foob')
})

test('with empty list', () => {
  expect(dropLastWhile(() => true, [])).toEqual([])
  expect(dropLastWhile(() => false, [])).toEqual([])
})

const possiblePredicates = [
  x => x > 2,
  x => x < 2,
  x => x < -2,
  x => x > 10,
  '',
  [],
  [ 1 ],
]

const possibleIterables = [
  list,
  [ {}, '1', 2 ],
  str,
  `${ str }${ str }`,
  /foo/g,
  Promise.resolve('foo'),
  2,
]

describe('brute force', () => {
  compareCombinations({
    fn          : dropLastWhile,
    fnRamda     : dropLastWhileRamda,
    firstInput  : possiblePredicates,
    secondInput : possibleIterables,
    callback    : errorsCounters => {
      expect(errorsCounters).toMatchInlineSnapshot(`
        {
          "ERRORS_MESSAGE_MISMATCH": 0,
          "ERRORS_TYPE_MISMATCH": 12,
          "RESULTS_MISMATCH": 0,
          "SHOULD_NOT_THROW": 21,
          "SHOULD_THROW": 0,
          "TOTAL_TESTS": 49,
        }
      `)
    },
  })
})

---------------

dropRepeats

dropRepeats<T>(list: T[]): T[]

It removes any successive duplicates according to R.equals.

const result = R.dropRepeats([
  1, 
  1, 
  {a: 1}, 
  {a:1}, 
  1
])
// => [1, {a: 1}, 1]

Try this R.dropRepeats example in Rambda REPL

All TypeScript definitions
dropRepeats<T>(list: T[]): T[];
R.dropRepeats source
import { isArray } from './_internals/isArray.js'
import { equals } from './equals.js'

export function dropRepeats(list){
  if (!isArray(list)){
    throw new Error(`${ list } is not a list`)
  }

  const toReturn = []

  list.reduce((prev, current) => {
    if (!equals(prev, current)){
      toReturn.push(current)
    }

    return current
  }, undefined)

  return toReturn
}
Tests
import { dropRepeats as dropRepeatsRamda } from 'ramda'

import { compareCombinations } from './_internals/testUtils.js'
import { add } from './add.js'
import { dropRepeats } from './dropRepeats.js'

const list = [ 1, 2, 2, 2, 3, 4, 4, 5, 5, 3, 2, 2, { a : 1 }, { a : 1 } ]
const listClean = [ 1, 2, 3, 4, 5, 3, 2, { a : 1 } ]

test('happy', () => {
  const result = dropRepeats(list)
  expect(result).toEqual(listClean)
})

const possibleLists = [
  [ add(1), async () => {}, [ 1 ], [ 1 ], [ 2 ], [ 2 ] ],
  [ add(1), add(1), add(2) ],
  [],
  1,
  /foo/g,
  Promise.resolve(1),
]

describe('brute force', () => {
  compareCombinations({
    firstInput : possibleLists,
    callback   : errorsCounters => {
      expect(errorsCounters).toMatchInlineSnapshot(`
        {
          "ERRORS_MESSAGE_MISMATCH": 0,
          "ERRORS_TYPE_MISMATCH": 0,
          "RESULTS_MISMATCH": 1,
          "SHOULD_NOT_THROW": 3,
          "SHOULD_THROW": 0,
          "TOTAL_TESTS": 6,
        }
      `)
    },
    fn      : dropRepeats,
    fnRamda : dropRepeatsRamda,
  })
})

---------------

dropRepeatsBy

dropRepeatsBy<T, U>(fn: (a: T) => U, list: T[]): T[]
const result = R.dropRepeatsBy(
  Math.abs,
  [1, -1, 2, 3, -3]
)
// => [1, 2, 3]

Try this R.dropRepeatsBy example in Rambda REPL

All TypeScript definitions
dropRepeatsBy<T, U>(fn: (a: T) => U, list: T[]): T[];
dropRepeatsBy<T, U>(
  fn: (a: T) => U
): (list: T[]) => T[];
dropRepeatsBy(fn: any): <T>(list: T[]) => T[];
R.dropRepeatsBy source
import { equals } from './equals.js'

export function dropRepeatsBy(fn, list){
  if (arguments.length === 1) return _list => dropRepeatsBy(fn, _list)

  let lastEvaluated = null

  return list.slice().filter(item => {
    if (lastEvaluated === null){
      lastEvaluated = fn(item)

      return true
    }
    const evaluatedResult = fn(item)
    if (equals(lastEvaluated, evaluatedResult)) return false

    lastEvaluated = evaluatedResult

    return true
  })
}
Tests
import { dropRepeatsBy } from './dropRepeatsBy.js'

test('happy', () => {
  const fn = ({ i }) => ({ i : Math.abs(i) })
  const objs = [ { i : 1 }, { i : 2 }, { i : 3 }, { i : -4 }, { i : 5 }, { i : 3 } ]
  const objs2 = [
    { i : 1 },
    { i : -1 },
    { i : 1 },
    { i : 2 },
    { i : 3 },
    { i : 3 },
    { i : -4 },
    { i : 4 },
    { i : 5 },
    { i : 3 },
  ]
  expect(dropRepeatsBy(fn, objs2)).toEqual(objs)
  expect(dropRepeatsBy(fn, objs)).toEqual(objs)
})

test('keeps elements from the left', () => {
  expect(dropRepeatsBy(({ n, ...rest }) => ({ ...rest }),
    [
      {
        i : 1,
        n : 1,
      },
      {
        i : 1,
        n : 2,
      },
      {
        i : 1,
        n : 3,
      },
      {
        i : 4,
        n : 1,
      },
      {
        i : 4,
        n : 2,
      },
    ])).toEqual([
    {
      i : 1,
      n : 1,
    },
    {
      i : 4,
      n : 1,
    },
  ])
})

test('returns an empty array for an empty array', () => {
  expect(dropRepeatsBy(() => {}, [])).toEqual([])
})

---------------

dropRepeatsWith

dropRepeatsWith<T>(predicate: (x: T, y: T) => boolean, list: T[]): T[]
const list = [{a:1,b:2}, {a:1,b:3}, {a:2, b:4}]
const result = R.dropRepeatsWith(R.prop('a'), list)

// => [{a:1,b:2}, {a:2, b:4}]

Try this R.dropRepeatsWith example in Rambda REPL

All TypeScript definitions
dropRepeatsWith<T>(predicate: (x: T, y: T) => boolean, list: T[]): T[];
dropRepeatsWith<T>(predicate: (x: T, y: T) => boolean): (list: T[]) => T[];
R.dropRepeatsWith source
import { isArray } from './_internals/isArray.js'

export function dropRepeatsWith(predicate, list){
  if (arguments.length === 1){
    return _iterable => dropRepeatsWith(predicate, _iterable)
  }

  if (!isArray(list)){
    throw new Error(`${ list } is not a list`)
  }

  const toReturn = []

  list.reduce((prev, current) => {
    if (prev === undefined){
      toReturn.push(current)

      return current
    }
    if (!predicate(prev, current)){
      toReturn.push(current)
    }

    return current
  }, undefined)

  return toReturn
}
Tests
import { dropRepeatsWith as dropRepeatsWithRamda, eqProps } from 'ramda'

import { compareCombinations } from './_internals/testUtils.js'
import { dropRepeatsWith } from './dropRepeatsWith.js'
import { path } from './path.js'
import { prop } from './prop.js'

const eqI = eqProps('i')

test('happy', () => {
  const list = [ { i : 1 }, { i : 2 }, { i : 2 }, { i : 3 } ]
  const expected = [ { i : 1 }, { i : 2 }, { i : 3 } ]
  const result = dropRepeatsWith(eqI, list)
  expect(result).toEqual(expected)
})

test('readme example', () => {
  const list = [
    {
      a : 1,
      b : 2,
    },
    {
      a : 1,
      b : 3,
    },
    {
      a : 2,
      b : 4,
    },
  ]
  const result = dropRepeatsWith(prop('a'), list)
  expect(result).toEqual([
    {
      a : 1,
      b : 2,
    },
  ])
})

test('keeps elements from the left predicate input', () => {
  const list = [
    {
      i : 1,
      n : 1,
    },
    {
      i : 1,
      n : 2,
    },
    {
      i : 1,
      n : 3,
    },
    {
      i : 4,
      n : 1,
    },
    {
      i : 4,
      n : 2,
    },
  ]
  const expected = [
    {
      i : 1,
      n : 1,
    },
    {
      i : 4,
      n : 1,
    },
  ]
  const result = dropRepeatsWith(eqI)(list)
  expect(result).toEqual(expected)
})

const possiblePredicates = [
  null,
  undefined,
  x => x + 1,
  x => true,
  x => false,
  x => '',
  path([ 'a', 'b' ]),
]
const possibleLists = [
  null,
  undefined,
  [],
  [ 1 ],
  [ { a : { b : 1 } }, { a : { b : 1 } } ],
  [ /foo/g, /foo/g ],
]

describe('brute force', () => {
  compareCombinations({
    firstInput  : possiblePredicates,
    secondInput : possibleLists,
    callback    : errorsCounters => {
      expect(errorsCounters).toMatchInlineSnapshot(`
        {
          "ERRORS_MESSAGE_MISMATCH": 4,
          "ERRORS_TYPE_MISMATCH": 14,
          "RESULTS_MISMATCH": 0,
          "SHOULD_NOT_THROW": 0,
          "SHOULD_THROW": 0,
          "TOTAL_TESTS": 42,
        }
      `)
    },
    fn      : dropRepeatsWith,
    fnRamda : dropRepeatsWithRamda,
  })
})

---------------

dropWhile

dropWhile(fn: Predicate<string>, iterable: string): string
const list = [1, 2, 3, 4]
const predicate = x => x < 3
const result = R.dropWhile(predicate, list)
// => [3, 4]

Try this R.dropWhile example in Rambda REPL

All TypeScript definitions
dropWhile(fn: Predicate<string>, iterable: string): string;
dropWhile(fn: Predicate<string>): (iterable: string) => string;
dropWhile<T>(fn: Predicate<T>, iterable: T[]): T[];
dropWhile<T>(fn: Predicate<T>): (iterable: T[]) => T[];
R.dropWhile source
import { isArray as isArrayMethod } from './_internals/isArray.js'

export function dropWhile(predicate, iterable){
  if (arguments.length === 1){
    return _iterable => dropWhile(predicate, _iterable)
  }
  const isArray = isArrayMethod(iterable)
  if (!isArray && typeof iterable !== 'string'){
    throw new Error('`iterable` is neither list nor a string')
  }

  const toReturn = []
  let counter = 0

  while (counter < iterable.length){
    const item = iterable[ counter++ ]
    if (!predicate(item)){
      toReturn.push(item)
      break
    }
  }

  while (counter < iterable.length){
    toReturn.push(iterable[ counter++ ])
  }

  return isArray ? toReturn : toReturn.join('')
}
Tests
import { dropWhile as dropWhileRamda } from 'ramda'

import { compareCombinations } from './_internals/testUtils.js'
import { dropWhile } from './dropWhile.js'

const list = [ 1, 2, 3, 4 ]

test('happy', () => {
  const predicate = x => x < 3
  const result = dropWhile(predicate, list)
  expect(result).toEqual([ 3, 4 ])
})

test('always true', () => {
  const predicate = () => true
  const result = dropWhileRamda(predicate, list)
  expect(result).toEqual([])
})

test('always false', () => {
  const predicate = () => 0
  const result = dropWhile(predicate)(list)
  expect(result).toEqual(list)
})

test('works with string as iterable', () => {
  const iterable = 'foobar'
  const predicate = x => x !== 'b'
  const result = dropWhile(predicate, iterable)
  expect(result).toBe('bar')
})

const possiblePredicates = [
  null,
  undefined,
  () => 0,
  () => true,
  /foo/g,
  {},
  [],
]

const possibleIterables = [
  null,
  undefined,
  [],
  {},
  1,
  '',
  'foobar',
  [ '' ],
  [ 1, 2, 3, 4, 5 ],
]

describe('brute force', () => {
  compareCombinations({
    firstInput : possiblePredicates,
    callback   : errorsCounters => {
      expect(errorsCounters).toMatchInlineSnapshot(`
        {
          "ERRORS_MESSAGE_MISMATCH": 15,
          "ERRORS_TYPE_MISMATCH": 14,
          "RESULTS_MISMATCH": 0,
          "SHOULD_NOT_THROW": 14,
          "SHOULD_THROW": 0,
          "TOTAL_TESTS": 63,
        }
      `)
    },
    secondInput : possibleIterables,
    fn          : dropWhile,
    fnRamda     : dropWhileRamda,
  })
})

---------------

either

either(firstPredicate: Pred, secondPredicate: Pred): Pred

It returns a new predicate function from firstPredicate and secondPredicate inputs.

This predicate function will return true, if any of the two input predicates return true.

const firstPredicate = x => x > 10
const secondPredicate = x => x % 2 === 0
const predicate = R.either(firstPredicate, secondPredicate)

const result = [
  predicate(15),
  predicate(8),
  predicate(7),
]
// => [true, true, false]

Try this R.either example in Rambda REPL

All TypeScript definitions
either(firstPredicate: Pred, secondPredicate: Pred): Pred;
either<T>(firstPredicate: Predicate<T>, secondPredicate: Predicate<T>): Predicate<T>;
either<T>(firstPredicate: Predicate<T>): (secondPredicate: Predicate<T>) => Predicate<T>;
either(firstPredicate: Pred): (secondPredicate: Pred) => Pred;
R.either source
export function either(firstPredicate, secondPredicate){
  if (arguments.length === 1){
    return _secondPredicate => either(firstPredicate, _secondPredicate)
  }

  return (...input) =>
    Boolean(firstPredicate(...input) || secondPredicate(...input))
}
Tests
import { either } from './either.js'

test('with multiple inputs', () => {
  const between = function (
    a, b, c
  ){
    return a < b && b < c
  }
  const total20 = function (
    a, b, c
  ){
    return a + b + c === 20
  }
  const fn = either(between, total20)
  expect(fn(
    7, 8, 5
  )).toBeTrue()
})

test('skip evaluation of the second expression', () => {
  let effect = 'not evaluated'
  const F = function (){
    return true
  }
  const Z = function (){
    effect = 'Z got evaluated'
  }
  either(F, Z)()

  expect(effect).toBe('not evaluated')
})

test('case 1', () => {
  const firstFn = val => val > 0
  const secondFn = val => val * 5 > 10

  expect(either(firstFn, secondFn)(1)).toBeTrue()
})

test('case 2', () => {
  const firstFn = val => val > 0
  const secondFn = val => val === -10
  const fn = either(firstFn)(secondFn)

  expect(fn(-10)).toBeTrue()
})

---------------

empty

empty<T>(x: T): T
const result = [R.empty([1,2,3]), R.empty('foo'), R.empty({x: 1, y: 2})]
// => [[], '', {}]

Try this R.empty example in Rambda REPL

All TypeScript definitions
empty<T>(x: T): T;
R.empty source
import { type } from './type.js'

export function empty(list){
  if (typeof list === 'string') return ''

  if (Array.isArray(list)){
    const { name } = list.constructor
    if (name === 'Uint8Array') return Uint8Array.from('')

    if (name === 'Float32Array') return new Float32Array([])

    return []
  }
  if (type(list) === 'Object') return {}
}
Tests
import { empty } from 'ramda'

test('returns empty array given array', () => {
  expect(empty([ 1, 2, 3 ])).toEqual([])
})

test('returns empty array of equivalent type given typed array', () => {
  expect(empty(Uint8Array.from('123'))).toEqual(Uint8Array.from(''))
  expect(empty(Uint8Array.from('123')).constructor.name).toBe('Uint8Array')
  expect(empty(new Float32Array([ 1, 2, 3 ]))).toEqual(new Float32Array([]))
  expect(empty(new Float32Array([ 1, 2, 3 ])).constructor.name).toBe('Float32Array')
})

test('returns empty string given string', () => {
  expect(empty('abc')).toBe('')
  expect(empty(new String('abc'))).toBe('')
})

test('other types', () => {
  expect(empty({ a : 1 })).toEqual({})
  expect(empty(/foo/g)).toBeUndefined()
})

---------------

endsWith

endsWith<T extends string>(question: T, str: string): boolean

When iterable is a string, then it behaves as String.prototype.endsWith. When iterable is a list, then it uses R.equals to determine if the target list ends in the same way as the given target.

const str = 'foo-bar'
const list = [{a:1}, {a:2}, {a:3}]

const result = [
  R.endsWith('bar', str),
  R.endsWith([{a:1}, {a:2}], list)
]
// => [true, true]

Try this R.endsWith example in Rambda REPL

All TypeScript definitions
endsWith<T extends string>(question: T, str: string): boolean;
endsWith<T extends string>(question: T): (str: string) => boolean;
endsWith<T>(question: T[], list: T[]): boolean;
endsWith<T>(question: T[]): (list: T[]) => boolean;
R.endsWith source
import { isArray } from './_internals/isArray.js'
import { equals } from './equals.js'

export function endsWith(target, iterable){
  if (arguments.length === 1) return _iterable => endsWith(target, _iterable)

  if (typeof iterable === 'string'){
    return iterable.endsWith(target)
  }
  if (!isArray(target)) return false

  const diff = iterable.length - target.length
  let correct = true
  const filtered = target.filter((x, index) => {
    if (!correct) return false
    const result = equals(x, iterable[ index + diff ])
    if (!result) correct = false

    return result
  })

  return filtered.length === target.length
}
Tests
import { endsWith as endsWithRamda } from 'ramda'

import { compareCombinations } from './_internals/testUtils.js'
import { endsWith } from './endsWith.js'

test('with string', () => {
  expect(endsWith('bar', 'foo-bar')).toBeTrue()
  expect(endsWith('baz')('foo-bar')).toBeFalse()
})

test('use R.equals with array', () => {
  const list = [ { a : 1 }, { a : 2 }, { a : 3 } ]
  expect(endsWith({ a : 3 }, list)).toBeFalse(),
  expect(endsWith([ { a : 3 } ], list)).toBeTrue()
  expect(endsWith([ { a : 2 }, { a : 3 } ], list)).toBeTrue()
  expect(endsWith(list, list)).toBeTrue()
  expect(endsWith([ { a : 1 } ], list)).toBeFalse()
})

export const possibleTargets = [
  NaN,
  [ NaN ],
  /foo/,
  [ /foo/ ],
  Promise.resolve(1),
  [ Promise.resolve(1) ],
  Error('foo'),
  [ Error('foo') ],
]

export const possibleIterables = [
  [ Promise.resolve(1), Promise.resolve(2) ],
  [ /foo/, /bar/ ],
  [ NaN ],
  [ Error('foo'), Error('bar') ],
]

describe('brute force', () => {
  compareCombinations({
    fn          : endsWith,
    fnRamda     : endsWithRamda,
    firstInput  : possibleTargets,
    secondInput : possibleIterables,
    callback    : errorsCounters => {
      expect(errorsCounters).toMatchInlineSnapshot(`
        {
          "ERRORS_MESSAGE_MISMATCH": 0,
          "ERRORS_TYPE_MISMATCH": 0,
          "RESULTS_MISMATCH": 0,
          "SHOULD_NOT_THROW": 0,
          "SHOULD_THROW": 0,
          "TOTAL_TESTS": 32,
        }
      `)
    },
  })
})

---------------

eqBy

eqBy<T>(fn: (a: T) => unknown, a: T, b: T): boolean
const result = R.eqBy(Math.abs, 5, -5)
// => true

Try this R.eqBy example in Rambda REPL

All TypeScript definitions
eqBy<T>(fn: (a: T) => unknown, a: T, b: T): boolean;
eqBy<T>(fn: (a: T) => unknown, a: T): (b: T) => boolean;
eqBy<T>(fn: (a: T) => unknown): {
  (a: T, b: T): boolean;
  (a: T): (b: T) => boolean;
};
R.eqBy source
import { curry } from './curry.js'
import { equals } from './equals.js'

export function eqByFn(
  fn, a, b
){
  return equals(fn(a), fn(b))
}

export const eqBy = curry(eqByFn)
Tests
import { eqByFn } from './eqBy.js'

test('deteremines whether two values map to the same value in the codomain', () => {
  expect(eqByFn(
    Math.abs, 5, 5
  )).toBe(true)
  expect(eqByFn(
    Math.abs, 5, -5
  )).toBe(true)
  expect(eqByFn(
    Math.abs, -5, 5
  )).toBe(true)
  expect(eqByFn(
    Math.abs, -5, -5
  )).toBe(true)
  expect(eqByFn(
    Math.abs, 42, 99
  )).toBe(false)
})

test('has R.equals semantics', () => {
  expect(eqByFn(
    Math.abs, NaN, NaN
  )).toBe(true)
  expect(eqByFn(
    Math.abs, [ 42 ], [ 42 ]
  )).toBe(true)
  expect(eqByFn(
    x => x, { a : 1 }, { a : 1 }
  )).toBe(true)
  expect(eqByFn(
    x => x, { a : 1 }, { a : 2 }
  )).toBe(false)
})

---------------

eqProps

eqProps<T, U>(prop: string, obj1: T, obj2: U): boolean

It returns true if property prop in obj1 is equal to property prop in obj2 according to R.equals.

const obj1 = {a: 1, b:2}
const obj2 = {a: 1, b:3}
const result = R.eqProps('a', obj1, obj2)
// => true

Try this R.eqProps example in Rambda REPL

All TypeScript definitions
eqProps<T, U>(prop: string, obj1: T, obj2: U): boolean;
eqProps<P extends string>(prop: P): <T, U>(obj1: Record<P, T>, obj2: Record<P, U>) => boolean;
eqProps<T>(prop: string, obj1: T): <U>(obj2: U) => boolean;
R.eqProps source
import { curry } from './curry.js'
import { equals } from './equals.js'
import { prop } from './prop.js'

function eqPropsFn(
  property, objA, objB
){
  return equals(prop(property, objA), prop(property, objB))
}

export const eqProps = curry(eqPropsFn)
Tests
import { eqProps as eqPropsRamda } from 'ramda'

import { compareCombinations } from './_internals/testUtils.js'
import { eqProps } from './eqProps.js'

const obj1 = {
  a : 1,
  b : 2,
}
const obj2 = {
  a : 1,
  b : 3,
}

test('props are equal', () => {
  const result = eqProps(
    'a', obj1, obj2
  )
  expect(result).toBeTrue()
})

test('props are not equal', () => {
  const result = eqProps(
    'b', obj1, obj2
  )
  expect(result).toBeFalse()
})

test('prop does not exist', () => {
  const result = eqProps(
    'c', obj1, obj2
  )
  expect(result).toBeTrue()
})

test('can handle null or undefined object', () => {
  expect(eqProps(
    'value', { value : 0 }, null
  )).toBeFalse()
  expect(eqProps(
    'value', { value : 0 }, undefined
  )).toBeFalse()
  expect(eqProps(
    'value', null, { value : 0 }
  )).toBeFalse()
  expect(eqProps(
    'value', undefined, { value : 0 }
  )).toBeFalse()
  expect(eqProps(
    'value', undefined, { value : undefined }
  )).toBeTrue()
  expect(eqProps(
    'value', null, { value : undefined }
  )).toBeTrue()
  expect(eqProps(
    'value', { value : undefined }, undefined
  )).toBeTrue()
  expect(eqProps(
    'value', { value : undefined }, null
  )).toBeTrue()
  expect(eqProps(
    'value', {}, null
  )).toBeTrue()
  expect(eqProps(
    'value', {}, undefined
  )).toBeTrue()
  expect(eqProps(
    'value', null, {}
  )).toBeTrue()
  expect(eqProps(
    'value', undefined, {}
  )).toBeTrue()
})

const possibleProps = [ 'a', 'a.b', null, false, 0, 1, {}, [] ]

const possibleObjects = [
  { a : 1 },
  {
    a : 1,
    b : 2,
  },
  {},
  [],
  null,
  {
    a : { b : 1 },
    c : 2,
  },
  {
    a : { b : 1 },
    c : 3,
  },
  { a : { b : 2 } },
]

describe('brute force', () => {
  let totalTestsCounter = 0

  compareCombinations({
    firstInput : possibleProps,
    setCounter : () => totalTestsCounter++,
    callback   : errorsCounters => {
      expect(errorsCounters).toMatchInlineSnapshot(`
        {
          "ERRORS_MESSAGE_MISMATCH": 0,
          "ERRORS_TYPE_MISMATCH": 0,
          "RESULTS_MISMATCH": 0,
          "SHOULD_NOT_THROW": 0,
          "SHOULD_THROW": 120,
          "TOTAL_TESTS": 512,
        }
      `)
    },
    secondInput : possibleObjects,
    thirdInput  : possibleObjects,
    fn          : eqProps,
    fnRamda     : eqPropsRamda,
  })
})

---------------

equals

equals<T>(x: T, y: T): boolean

It deeply compares x and y and returns true if they are equal.

💥 It doesn't handle cyclical data structures and functions

R.equals(
  [1, {a:2}, [{b: 3}]],
  [1, {a:2}, [{b: 3}]]
) // => true

Try this R.equals example in Rambda REPL

All TypeScript definitions
equals<T>(x: T, y: T): boolean;
equals<T>(x: T): (y: T) => boolean;
R.equals source
import { isArray } from './_internals/isArray.js'
import { type } from './type.js'

export function _lastIndexOf(valueToFind, list){
  if (!isArray(list))
    throw new Error(`Cannot read property 'indexOf' of ${ list }`)

  const typeOfValue = type(valueToFind)
  if (![ 'Array', 'NaN', 'Object', 'RegExp' ].includes(typeOfValue))
    return list.lastIndexOf(valueToFind)

  const { length } = list
  let index = length
  let foundIndex = -1

  while (--index > -1 && foundIndex === -1)
    if (equals(list[ index ], valueToFind))
      foundIndex = index

  return foundIndex
}

export function _indexOf(valueToFind, list){
  if (!isArray(list))
    throw new Error(`Cannot read property 'indexOf' of ${ list }`)

  const typeOfValue = type(valueToFind)
  if (![ 'Array', 'NaN', 'Object', 'RegExp' ].includes(typeOfValue))
    return list.indexOf(valueToFind)

  let index = -1
  let foundIndex = -1
  const { length } = list

  while (++index < length && foundIndex === -1)
    if (equals(list[ index ], valueToFind))
      foundIndex = index

  return foundIndex
}

function _arrayFromIterator(iter){
  const list = []
  let next
  while (!(next = iter.next()).done)
    list.push(next.value)

  return list
}

function _compareSets(a, b){
  if (a.size !== b.size)
    return false

  const aList = _arrayFromIterator(a.values())
  const bList = _arrayFromIterator(b.values())

  const filtered = aList.filter(aInstance => _indexOf(aInstance, bList) === -1)

  return filtered.length === 0
}

function compareErrors(a, b){
  if (a.message !== b.message) return false
  if (a.toString !== b.toString) return false

  return a.toString() === b.toString()
}

function parseDate(maybeDate){
  if (!maybeDate.toDateString) return [ false ]

  return [ true, maybeDate.getTime() ]
}

function parseRegex(maybeRegex){
  if (maybeRegex.constructor !== RegExp) return [ false ]

  return [ true, maybeRegex.toString() ]
}

export function equals(a, b){
  if (arguments.length === 1) return _b => equals(a, _b)

  if (Object.is(a, b)) return true

  const aType = type(a)

  if (aType !== type(b)) return false
  if (aType === 'Function')
    return a.name === undefined ? false : a.name === b.name

  if ([ 'NaN', 'Null', 'Undefined' ].includes(aType)) return true

  if ([ 'BigInt', 'Number' ].includes(aType)){
    if (Object.is(-0, a) !== Object.is(-0, b)) return false

    return a.toString() === b.toString()
  }

  if ([ 'Boolean', 'String' ].includes(aType))
    return a.toString() === b.toString()

  if (aType === 'Array'){
    const aClone = Array.from(a)
    const bClone = Array.from(b)

    if (aClone.toString() !== bClone.toString())
      return false

    let loopArrayFlag = true
    aClone.forEach((aCloneInstance, aCloneIndex) => {
      if (loopArrayFlag)
        if (
          aCloneInstance !== bClone[ aCloneIndex ] &&
          !equals(aCloneInstance, bClone[ aCloneIndex ])
        )
          loopArrayFlag = false

    })

    return loopArrayFlag
  }

  const aRegex = parseRegex(a)
  const bRegex = parseRegex(b)

  if (aRegex[ 0 ])
    return bRegex[ 0 ] ? aRegex[ 1 ] === bRegex[ 1 ] : false
  else if (bRegex[ 0 ]) return false

  const aDate = parseDate(a)
  const bDate = parseDate(b)

  if (aDate[ 0 ])
    return bDate[ 0 ] ? aDate[ 1 ] === bDate[ 1 ] : false
  else if (bDate[ 0 ]) return false

  if (a instanceof Error){
    if (!(b instanceof Error)) return false

    return compareErrors(a, b)
  }

  if (aType === 'Set')
    return _compareSets(a, b)

  if (aType === 'Object'){
    const aKeys = Object.keys(a)

    if (aKeys.length !== Object.keys(b).length)
      return false

    let loopObjectFlag = true
    aKeys.forEach(aKeyInstance => {
      if (loopObjectFlag){
        const aValue = a[ aKeyInstance ]
        const bValue = b[ aKeyInstance ]

        if (aValue !== bValue && !equals(aValue, bValue))
          loopObjectFlag = false

      }
    })

    return loopObjectFlag
  }

  return false
}
Tests
import { equals as equalsRamda } from 'ramda'

import { compareCombinations } from './_internals/testUtils.js'
import { variousTypes } from './benchmarks/_utils.js'
import { equals } from './equals.js'

test('compare functions', () => {
  function foo(){}
  function bar(){}
  const baz = () => {}

  const expectTrue = equals(foo, foo)
  const expectFalseFirst = equals(foo, bar)
  const expectFalseSecond = equals(foo, baz)

  expect(expectTrue).toBeTrue()
  expect(expectFalseFirst).toBeFalse()
  expect(expectFalseSecond).toBeFalse()
})

test('with array of objects', () => {
  const list1 = [ { a : 1 }, [ { b : 2 } ] ]
  const list2 = [ { a : 1 }, [ { b : 2 } ] ]
  const list3 = [ { a : 1 }, [ { b : 3 } ] ]

  expect(equals(list1, list2)).toBeTrue()
  expect(equals(list1, list3)).toBeFalse()
})

test('with regex', () => {
  expect(equals(/s/, /s/)).toBeTrue()
  expect(equals(/s/, /d/)).toBeFalse()
  expect(equals(/a/gi, /a/gi)).toBeTrue()
  expect(equals(/a/gim, /a/gim)).toBeTrue()
  expect(equals(/a/gi, /a/i)).toBeFalse()
})

test('not a number', () => {
  expect(equals([ NaN ], [ NaN ])).toBeTrue()
})

test('new number', () => {
  expect(equals(new Number(0), new Number(0))).toBeTrue()
  expect(equals(new Number(0), new Number(1))).toBeFalse()
  expect(equals(new Number(1), new Number(0))).toBeFalse()
})

test('new string', () => {
  expect(equals(new String(''), new String(''))).toBeTrue()
  expect(equals(new String(''), new String('x'))).toBeFalse()
  expect(equals(new String('x'), new String(''))).toBeFalse()
  expect(equals(new String('foo'), new String('foo'))).toBeTrue()
  expect(equals(new String('foo'), new String('bar'))).toBeFalse()
  expect(equals(new String('bar'), new String('foo'))).toBeFalse()
})

test('new Boolean', () => {
  expect(equals(new Boolean(true), new Boolean(true))).toBeTrue()
  expect(equals(new Boolean(false), new Boolean(false))).toBeTrue()
  expect(equals(new Boolean(true), new Boolean(false))).toBeFalse()
  expect(equals(new Boolean(false), new Boolean(true))).toBeFalse()
})

test('new Error', () => {
  expect(equals(new Error('XXX'), {})).toBeFalse()
  expect(equals(new Error('XXX'), new TypeError('XXX'))).toBeFalse()
  expect(equals(new Error('XXX'), new Error('YYY'))).toBeFalse()
  expect(equals(new Error('XXX'), new Error('XXX'))).toBeTrue()
  expect(equals(new Error('XXX'), new TypeError('YYY'))).toBeFalse()
  expect(equals(new Error('XXX'), new Error('XXX'))).toBeTrue()
})

test('with dates', () => {
  expect(equals(new Date(0), new Date(0))).toBeTrue()
  expect(equals(new Date(1), new Date(1))).toBeTrue()
  expect(equals(new Date(0), new Date(1))).toBeFalse()
  expect(equals(new Date(1), new Date(0))).toBeFalse()
  expect(equals(new Date(0), {})).toBeFalse()
  expect(equals({}, new Date(0))).toBeFalse()
})

test('ramda spec', () => {
  expect(equals({}, {})).toBeTrue()

  expect(equals({
    a : 1,
    b : 2,
  },
  {
    a : 1,
    b : 2,
  })).toBeTrue()

  expect(equals({
    a : 2,
    b : 3,
  },
  {
    a : 2,
    b : 3,
  })).toBeTrue()

  expect(equals({
    a : 2,
    b : 3,
  },
  {
    a : 3,
    b : 3,
  })).toBeFalse()

  expect(equals({
    a : 2,
    b : 3,
    c : 1,
  },
  {
    a : 2,
    b : 3,
  })).toBeFalse()
})

test('works with boolean tuple', () => {
  expect(equals([ true, false ], [ true, false ])).toBeTrue()
  expect(equals([ true, false ], [ true, true ])).toBeFalse()
})

test('works with equal objects within array', () => {
  const objFirst = {
    a : {
      b : 1,
      c : 2,
      d : [ 1 ],
    },
  }
  const objSecond = {
    a : {
      b : 1,
      c : 2,
      d : [ 1 ],
    },
  }

  const x = [ 1, 2, objFirst, null, '', [] ]
  const y = [ 1, 2, objSecond, null, '', [] ]
  expect(equals(x, y)).toBeTrue()
})

test('works with different objects within array', () => {
  const objFirst = { a : { b : 1 } }
  const objSecond = { a : { b : 2 } }

  const x = [ 1, 2, objFirst, null, '', [] ]
  const y = [ 1, 2, objSecond, null, '', [] ]
  expect(equals(x, y)).toBeFalse()
})

test('works with undefined as second argument', () => {
  expect(equals(1, undefined)).toBeFalse()

  expect(equals(undefined, undefined)).toBeTrue()
})

test('compare sets', () => {
  const toCompareDifferent = new Set([ { a : 1 }, { a : 2 } ])
  const toCompareSame = new Set([ { a : 1 }, { a : 2 }, { a : 1 } ])
  const testSet = new Set([ { a : 1 }, { a : 2 }, { a : 1 } ])
  expect(equals(toCompareSame, testSet)).toBeTruthy()
  expect(equals(toCompareDifferent, testSet)).toBeFalsy()
  expect(equalsRamda(toCompareSame, testSet)).toBeTruthy()
  expect(equalsRamda(toCompareDifferent, testSet)).toBeFalsy()
})

test('compare simple sets', () => {
  const testSet = new Set([ '2', '3', '3', '2', '1' ])
  expect(equals(new Set([ '3', '2', '1' ]), testSet)).toBeTruthy()
  expect(equals(new Set([ '3', '2', '0' ]), testSet)).toBeFalsy()
})

test('various examples', () => {
  expect(equals([ 1, 2, 3 ])([ 1, 2, 3 ])).toBeTrue()

  expect(equals([ 1, 2, 3 ], [ 1, 2 ])).toBeFalse()

  expect(equals(1, 1)).toBeTrue()

  expect(equals(1, '1')).toBeFalse()

  expect(equals({}, {})).toBeTrue()

  expect(equals({
    a : 1,
    b : 2,
  },
  {
    a : 1,
    b : 2,
  })).toBeTrue()

  expect(equals({
    a : 1,
    b : 2,
  },
  {
    a : 1,
    b : 1,
  })).toBeFalse()

  expect(equals({
    a : 1,
    b : false,
  },
  {
    a : 1,
    b : 1,
  })).toBeFalse()

  expect(equals({
    a : 1,
    b : 2,
  },
  {
    a : 1,
    b : 2,
    c : 3,
  })).toBeFalse()

  expect(equals({
    x : {
      a : 1,
      b : 2,
    },
  },
  {
    x : {
      a : 1,
      b : 2,
      c : 3,
    },
  })).toBeFalse()

  expect(equals({
    a : 1,
    b : 2,
  },
  {
    a : 1,
    b : 3,
  })).toBeFalse()

  expect(equals({ a : { b : { c : 1 } } }, { a : { b : { c : 1 } } })).toBeTrue()

  expect(equals({ a : { b : { c : 1 } } }, { a : { b : { c : 2 } } })).toBeFalse()

  expect(equals({ a : {} }, { a : {} })).toBeTrue()

  expect(equals('', '')).toBeTrue()

  expect(equals('foo', 'foo')).toBeTrue()

  expect(equals('foo', 'bar')).toBeFalse()

  expect(equals(0, false)).toBeFalse()

  expect(equals(/\s/g, null)).toBeFalse()

  expect(equals(null, null)).toBeTrue()

  expect(equals(false)(null)).toBeFalse()
})

test('with custom functions', () => {
  function foo(){
    return 1
  }
  foo.prototype.toString = () => ''
  const result = equals(foo, foo)

  expect(result).toBeTrue()
})

test('with classes', () => {
  class Foo{}
  const foo = new Foo()
  const result = equals(foo, foo)

  expect(result).toBeTrue()
})

test('with negative zero', () => {
  expect(equals(-0, -0)).toBeTrue()
  expect(equals(-0, 0)).toBeFalse()
  expect(equals(0, 0)).toBeTrue()
  expect(equals(-0, 1)).toBeFalse()
})

test('with big int', () => {
  const a = BigInt(9007199254740991)
  const b = BigInt(9007199254740991)
  const c = BigInt(7007199254740991)
  expect(equals(a, b)).toBeTrue()
  expect(equals(a, c)).toBeFalse()
})

describe('brute force', () => {
  compareCombinations({
    callback : errorsCounters => {
      expect(errorsCounters).toMatchInlineSnapshot(`
{
  "ERRORS_MESSAGE_MISMATCH": 0,
  "ERRORS_TYPE_MISMATCH": 0,
  "RESULTS_MISMATCH": 0,
  "SHOULD_NOT_THROW": 0,
  "SHOULD_THROW": 0,
  "TOTAL_TESTS": 289,
}
`)
    },
    firstInput  : variousTypes,
    fn          : equals,
    fnRamda     : equalsRamda,
    secondInput : variousTypes,
  })
})

---------------

evolve

evolve<T, U>(rules: ((x: T) => U)[], list: T[]): U[]

It takes object or array of functions as set of rules. These rules are applied to the iterable input to produce the result.

💥 Error handling of this method differs between Ramda and Rambda. Ramda for some wrong inputs returns result and for other - it returns one of the inputs. Rambda simply throws when inputs are not correct. Full details for this mismatch are listed in source/_snapshots/evolve.spec.js.snap file.

const rules = {
  foo : add(1),
  bar : add(-1),
}
const input = {
  a   : 1,
  foo : 2,
  bar : 3,
}
const result = evolve(rules, input)
const expected = {
  a   : 1,
  foo : 3,
  bar : 2,
})
// => `result` is equal to `expected`

Try this R.evolve example in Rambda REPL

All TypeScript definitions
evolve<T, U>(rules: ((x: T) => U)[], list: T[]): U[];
evolve<T, U>(rules: ((x: T) => U)[]) : (list: T[]) => U[];
evolve<E extends Evolver, V extends Evolvable<E>>(rules: E, obj: V): Evolve<V, E>;
evolve<E extends Evolver>(rules: E): <V extends Evolvable<E>>(obj: V) => Evolve<V, E>;
R.evolve source
import { isArray } from './_internals/isArray.js'
import { mapArray, mapObject } from './map.js'
import { type } from './type.js'

export function evolveArray(rules, list){
  return mapArray(
    (x, i) => {
      if (type(rules[ i ]) === 'Function'){
        return rules[ i ](x)
      }

      return x
    },
    list,
    true
  )
}

export function evolveObject(rules, iterable){
  return mapObject((x, prop) => {
    if (type(x) === 'Object'){
      const typeRule = type(rules[ prop ])
      if (typeRule === 'Function'){
        return rules[ prop ](x)
      }
      if (typeRule === 'Object'){
        return evolve(rules[ prop ], x)
      }

      return x
    }
    if (type(rules[ prop ]) === 'Function'){
      return rules[ prop ](x)
    }

    return x
  }, iterable)
}

export function evolve(rules, iterable){
  if (arguments.length === 1){
    return _iterable => evolve(rules, _iterable)
  }
  const rulesType = type(rules)
  const iterableType = type(iterable)

  if (iterableType !== rulesType){
    throw new Error('iterableType !== rulesType')
  }

  if (![ 'Object', 'Array' ].includes(rulesType)){
    throw new Error(`'iterable' and 'rules' are from wrong type ${ rulesType }`)
  }

  if (iterableType === 'Object'){
    return evolveObject(rules, iterable)
  }

  return evolveArray(rules, iterable)
}
Tests
import { evolve as evolveRamda } from 'ramda'

import { add } from '../rambda.js'
import { compareCombinations, compareToRamda } from './_internals/testUtils.js'
import { evolve } from './evolve.js'

test('happy', () => {
  const rules = {
    foo    : add(1),
    nested : { bar : x => Object.keys(x).length },
  }
  const input = {
    a      : 1,
    foo    : 2,
    nested : { bar : { z : 3 } },
  }
  const result = evolve(rules, input)
  expect(result).toEqual({
    a      : 1,
    foo    : 3,
    nested : { bar : 1 },
  })
})

test('nested rule is wrong', () => {
  const rules = {
    foo    : add(1),
    nested : { bar : 10 },
  }
  const input = {
    a      : 1,
    foo    : 2,
    nested : { bar : { z : 3 } },
  }
  const result = evolve(rules)(input)
  expect(result).toEqual({
    a      : 1,
    foo    : 3,
    nested : { bar : { z : 3 } },
  })
})

test('is recursive', () => {
  const rules = {
    nested : {
      second : add(-1),
      third  : add(1),
    },
  }
  const object = {
    first  : 1,
    nested : {
      second : 2,
      third  : 3,
    },
  }
  const expected = {
    first  : 1,
    nested : {
      second : 1,
      third  : 4,
    },
  }
  const result = evolve(rules, object)
  expect(result).toEqual(expected)
})

test('ignores primitive values', () => {
  const rules = {
    n : 2,
    m : 'foo',
  }
  const object = {
    n : 0,
    m : 1,
  }
  const expected = {
    n : 0,
    m : 1,
  }
  const result = evolve(rules, object)
  expect(result).toEqual(expected)
})

test('with array', () => {
  const rules = [ add(1), add(-1) ]
  const list = [ 100, 1400 ]
  const expected = [ 101, 1399 ]
  const result = evolve(rules, list)
  expect(result).toEqual(expected)
})

const rulesObject = { a : add(1) }
const rulesList = [ add(1) ]
const possibleIterables = [ null, undefined, '', 42, [], [ 1 ], { a : 1 } ]
const possibleRules = [ ...possibleIterables, rulesList, rulesObject ]

describe('brute force', () => {
  compareCombinations({
    firstInput : possibleRules,
    callback   : errorsCounters => {
      expect(errorsCounters).toMatchInlineSnapshot(`
        {
          "ERRORS_MESSAGE_MISMATCH": 0,
          "ERRORS_TYPE_MISMATCH": 4,
          "RESULTS_MISMATCH": 0,
          "SHOULD_NOT_THROW": 51,
          "SHOULD_THROW": 0,
          "TOTAL_TESTS": 63,
        }
      `)
    },
    secondInput : possibleIterables,
    fn          : evolve,
    fnRamda     : evolveRamda,
  })
})

---------------

excludes

excludes(valueToFind: string, input: string[] | string): boolean

Opposite of R.includes

R.equals is used to determine equality.

const result = [
  R.excludes('ar', 'foo'),
  R.excludes({a: 2}, [{a: 1}])
]
// => [true, true ]

Try this R.excludes example in Rambda REPL

All TypeScript definitions
excludes(valueToFind: string, input: string[] | string): boolean;
excludes(valueToFind: string): (input: string[] | string) => boolean;
excludes<T>(valueToFind: T, input: T[]): boolean;
excludes<T>(valueToFind: T): (input: T[]) => boolean;
R.excludes source
import { includes } from './includes.js'

export function excludes(valueToFind, input){
  if (arguments.length === 1) return _input => excludes(valueToFind, _input)

  return includes(valueToFind, input) === false
}
Tests
import { excludes } from './excludes.js'

test('excludes with string', () => {
  const str = 'more is less'

  expect(excludes('less')(str)).toBeFalse()
  expect(excludes('never', str)).toBeTrue()
})

test('excludes with array', () => {
  const arr = [ 1, 2, 3 ]

  expect(excludes(2)(arr)).toBeFalse()
  expect(excludes(4, arr)).toBeTrue()
})

---------------

F

F(): boolean
F() // => false

Try this R.F example in Rambda REPL

All TypeScript definitions
F(): boolean;
R.F source
export function F(){
  return false
}

---------------

filter

filter<T>(predicate: Predicate<T>): (input: T[]) => T[]

It filters list or object input using a predicate function.

const list = [3, 4, 3, 2]
const listPredicate = x => x > 2

const object = {abc: 'fo', xyz: 'bar', baz: 'foo'}
const objectPredicate = (x, prop) => x.length + prop.length > 5

const result = [
  R.filter(listPredicate, list),
  R.filter(objectPredicate, object)
]
// => [ [3, 4], { xyz: 'bar', baz: 'foo'} ]

Try this R.filter example in Rambda REPL

All TypeScript definitions
filter<T>(predicate: Predicate<T>): (input: T[]) => T[];
filter<T>(predicate: Predicate<T>, input: T[]): T[];
filter<T, U>(predicate: ObjectPredicate<T>): (x: Dictionary<T>) => Dictionary<T>;
filter<T>(predicate: ObjectPredicate<T>, x: Dictionary<T>): Dictionary<T>;
R.filter source
import { isArray } from './_internals/isArray.js'

export function filterObject(predicate, obj){
  const willReturn = {}

  for (const prop in obj){
    if (predicate(
      obj[ prop ], prop, obj
    )){
      willReturn[ prop ] = obj[ prop ]
    }
  }

  return willReturn
}

export function filterArray(
  predicate, list, indexed = false
){
  let index = 0
  const len = list.length
  const willReturn = []

  while (index < len){
    const predicateResult = indexed ?
      predicate(list[ index ], index) :
      predicate(list[ index ])
    if (predicateResult){
      willReturn.push(list[ index ])
    }

    index++
  }

  return willReturn
}

export function filter(predicate, iterable){
  if (arguments.length === 1)
    return _iterable => filter(predicate, _iterable)
  if (!iterable){
    throw new Error('Incorrect iterable input')
  }

  if (isArray(iterable)) return filterArray(
    predicate, iterable, false
  )

  return filterObject(predicate, iterable)
}
Tests
import { filter as filterRamda } from 'ramda'

import { filter } from './filter.js'
import { T } from './T.js'

const sampleObject = {
  a : 1,
  b : 2,
  c : 3,
  d : 4,
}

test('happy', () => {
  const isEven = n => n % 2 === 0

  expect(filter(isEven, [ 1, 2, 3, 4 ])).toEqual([ 2, 4 ])
  expect(filter(isEven, {
    a : 1,
    b : 2,
    d : 3,
  })).toEqual({ b : 2 })
})

test('predicate when input is object', () => {
  const obj = {
    a : 1,
    b : 2,
  }
  const predicate = (
    val, prop, inputObject
  ) => {
    expect(inputObject).toEqual(obj)
    expect(typeof prop).toBe('string')

    return val < 2
  }
  expect(filter(predicate, obj)).toEqual({ a : 1 })
})

test('with object', () => {
  const isEven = n => n % 2 === 0
  const result = filter(isEven, sampleObject)
  const expectedResult = {
    b : 2,
    d : 4,
  }

  expect(result).toEqual(expectedResult)
})

test('bad inputs difference between Ramda and Rambda', () => {
  expect(() => filter(T, null)).toThrowWithMessage(Error,
    'Incorrect iterable input')
  expect(() => filter(T)(undefined)).toThrowWithMessage(Error,
    'Incorrect iterable input')
  expect(() => filterRamda(T, null)).toThrowWithMessage(TypeError,
    'Cannot read properties of null (reading \'fantasy-land/filter\')')
  expect(() => filterRamda(T, undefined)).toThrowWithMessage(TypeError,
    'Cannot read properties of undefined (reading \'fantasy-land/filter\')')
})

---------------

filterArray

filterArray<T>(predicate: Predicate<T>): (input: T[]) => T[]
const result = R.filterArray(
  x => x > 1,
  [1, 2, 3]
)
// => [1, 3]

Try this R.filterArray example in Rambda REPL

All TypeScript definitions
filterArray<T>(predicate: Predicate<T>): (input: T[]) => T[];
filterArray<T>(predicate: Predicate<T>, input: T[]): T[];

---------------

filterAsync

filterAsync<T>(fn: AsyncPredicate<T>, list: T[]): Promise<T[]>

Asynchronous version of R.filter

const predicate = async x => {
  await R.delay(100)
  return x % 2 === 1
}
const result = await R.filterAsync(predicate, [ 1, 2, 3 ])
// => [ 1, 3 ]

Try this R.filterAsync example in Rambda REPL

All TypeScript definitions
filterAsync<T>(fn: AsyncPredicate<T>, list: T[]): Promise<T[]>;
filterAsync<T>(fn: AsyncPredicateIndexed<T>, list: T[]): Promise<T[]>;
filterAsync<T>(fn: AsyncPredicate<T>) : ( list: T[]) => Promise<T[]>;
filterAsync<T>(fn: AsyncPredicateIndexed<T>) : ( list: T[]) => Promise<T[]>;
R.filterAsync source
import { isArray } from './_internals/isArray.js'
import { filter } from './filter.js'
import { mapAsync } from './mapAsync.js'

export function filterAsyncFn(predicate, listOrObject){
  return new Promise((resolve, reject) => {
    mapAsync(predicate, listOrObject)
      .then(predicateResult => {
        if (isArray(predicateResult)){
          const filtered = listOrObject.filter((_, i) => predicateResult[ i ])

          return resolve(filtered)
        }
        const filtered = filter((_, prop) => predicateResult[ prop ],
          listOrObject)

        return resolve(filtered)
      })
      .catch(reject)
  })
}

export function filterAsync(predicate, listOrObject){
  if (arguments.length === 1){
    return async _listOrObject => filterAsyncFn(predicate, _listOrObject)
  }

  return new Promise((resolve, reject) => {
    filterAsyncFn(predicate, listOrObject).then(resolve)
      .catch(reject)
  })
}
Tests
import { delay } from './delay.js'
import { filterAsync } from './filterAsync.js'

test('happy', async () => {
  const predicate = async (x, i) => {
    expect(i).toBeNumber()
    await delay(100)

    return x % 2 === 1
  }
  const result = await filterAsync(predicate)([ 1, 2, 3 ])
  expect(result).toEqual([ 1, 3 ])
})

test('with object', async () => {
  const predicate = async (x, prop) => {
    expect(prop).toBeString()
    await delay(100)

    return x % 2 === 1
  }
  const result = await filterAsync(predicate, {
    a : 1,
    b : 2,
    c : 3,
    d : 4,
    e : 5,
  })

  expect(result).toEqual({
    a : 1,
    c : 3,
    e : 5,
  })
})

---------------

filterIndexed

filterIndexed<T>(predicate: IndexedPredicate<T>): (x: T[]) => T[]

Same as R.filter, but it passes index/property as second argument to the predicate, when looping over arrays/objects.

All TypeScript definitions
filterIndexed<T>(predicate: IndexedPredicate<T>): (x: T[]) => T[];
filterIndexed<T>(predicate: IndexedPredicate<T>, x: T[]): T[];
filterIndexed<T, U>(predicate: ObjectPredicate<T>): (x: Dictionary<T>) => Dictionary<T>;
filterIndexed<T>(predicate: ObjectPredicate<T>, x: Dictionary<T>): Dictionary<T>;
R.filterIndexed source
import { isArray } from './_internals/isArray.js'
import { filterArray, filterObject } from './filter.js'

export function filterIndexed(predicate, iterable){
  if (arguments.length === 1)
    return _iterable => filterIndexed(predicate, _iterable)
  if (!iterable) return []
  if (isArray(iterable)) return filterArray(
    predicate, iterable, true
  )

  return filterObject(predicate, iterable)
}
Tests
import { filter } from './filter.js'
import { filterIndexed } from './filterIndexed.js'

const iterator = (x, i) => {
  expect(x).toBeNumber()
  expect(i).toBeNumber()
}

test('happy', () => {
  const list = [ 1, 2, 3 ]
  filterIndexed(iterator, list)
  filterIndexed(iterator)(list)
})

test('with object', () => {
  const iterator = x => x + 1
  const obj = { a : 1 }
  expect(filterIndexed(iterator, obj)).toEqual(filter(iterator, obj))
})

test('with bad input', () => {
  expect(filterIndexed(iterator, undefined)).toEqual([])
})

---------------

filterObject

filterObject<T>(predicate: ObjectPredicate<T>): (x: Dictionary<T>) => Dictionary<T>
const obj = {a: 1, b:2}
const result = R.filterObject(
  x => x > 1,
  obj
)
// => {b: 2}

Try this R.filterObject example in Rambda REPL

All TypeScript definitions
filterObject<T>(predicate: ObjectPredicate<T>): (x: Dictionary<T>) => Dictionary<T>;
filterObject<T>(predicate: ObjectPredicate<T>, x: Dictionary<T>): Dictionary<T>;

---------------

find

find<T>(predicate: (x: T) => boolean, list: T[]): T | undefined

It returns the first element of list that satisfy the predicate.

If there is no such element, it returns undefined.

const predicate = x => R.type(x.foo) === 'Number'
const list = [{foo: 'bar'}, {foo: 1}]

const result = R.find(predicate, list)
// => {foo: 1}

Try this R.find example in Rambda REPL

All TypeScript definitions
find<T>(predicate: (x: T) => boolean, list: T[]): T | undefined;
find<T>(predicate: (x: T) => boolean): (list: T[]) => T | undefined;
R.find source
export function find(predicate, list){
  if (arguments.length === 1) return _list => find(predicate, _list)

  let index = 0
  const len = list.length

  while (index < len){
    const x = list[ index ]
    if (predicate(x)){
      return x
    }

    index++
  }
}
Tests
import { find } from './find.js'
import { propEq } from './propEq.js'

const list = [ { a : 1 }, { a : 2 }, { a : 3 } ]

test('happy', () => {
  const fn = propEq(2, 'a')
  expect(find(fn, list)).toEqual({ a : 2 })
})

test('with curry', () => {
  const fn = propEq(4, 'a')
  expect(find(fn)(list)).toBeUndefined()
})

test('with empty list', () => {
  expect(find(() => true, [])).toBeUndefined()
})

---------------

findAsync

findAsync<T>(predicate: (x: T) => Promise<boolean>, list: T[]): T | undefined

Asynchronous version of R.find.

const predicate = x => {
  await R.delay(100)
  return R.type(x.foo) === 'Number'
}

const list = [{foo: 'bar'}, {foo: 1}]

const result = await R.findAsync(predicate, list)
// => {foo: 1}

Try this R.findAsync example in Rambda REPL

All TypeScript definitions
findAsync<T>(predicate: (x: T) => Promise<boolean>, list: T[]): T | undefined;
findAsync<T>(predicate: (x: T) => Promise<boolean>): (list: T[]) => T | undefined;
R.findAsync source
import { isArray } from './_internals/isArray.js'
import { mapAsync } from './mapAsync.js'

export function findAsyncFn(predicate, list){
  return new Promise((resolve, reject) => {
    let canContinue = true
    let found

    const predicateFn = async (x, i) => {
      if (!canContinue) return false
      try {
        const result = await predicate(x, i)
        if (result){
          canContinue = false
          found = x
        }
      } catch (error){
        reject(error)
      }
    }

    mapAsync(predicateFn, list)
      .then(() => resolve(found))
      .catch(reject)
  })
}

export function findAsync(predicate, list){
  if (arguments.length === 1){
    return async _list => findAsync(predicate, _list)
  }

  return new Promise((resolve, reject) => {
    findAsyncFn(predicate, list).then(resolve)
      .catch(reject)
  })
}
Tests
import { findAsync } from './findAsync.js'
import { propEq } from './propEq.js'

const list = [ { a : 1 }, { a : 2 }, { a : 3 } ]

test('happy', async () => {
  const fn = async (x, i) => {
    expect(typeof i).toBe('number')

    return propEq(
      2, 'a', x
    )
  }
  await expect(findAsync(fn, list)).resolves.toEqual({ a : 2 })
  await expect(findAsync(fn)(list)).resolves.toEqual({ a : 2 })
  await expect(findAsync(fn)([])).resolves.toBeUndefined()
})

test('with error', async () => {
  const fn = async x => x.a.b.c === 1

  try {
    await findAsync(fn, list)
  } catch (error){
    expect(error.message).toBe('Cannot read properties of undefined (reading \'c\')')
  }
})

---------------

findIndex

findIndex<T>(predicate: (x: T) => boolean, list: T[]): number

It returns the index of the first element of list satisfying the predicate function.

If there is no such element, then -1 is returned.

const predicate = x => R.type(x.foo) === 'Number'
const list = [{foo: 'bar'}, {foo: 1}]

const result = R.findIndex(predicate, list)
// => 1

Try this R.findIndex example in Rambda REPL

All TypeScript definitions
findIndex<T>(predicate: (x: T) => boolean, list: T[]): number;
findIndex<T>(predicate: (x: T) => boolean): (list: T[]) => number;
R.findIndex source
export function findIndex(predicate, list){
  if (arguments.length === 1) return _list => findIndex(predicate, _list)

  const len = list.length
  let index = -1

  while (++index < len){
    if (predicate(list[ index ])){
      return index
    }
  }

  return -1
}
Tests
import { findIndex } from './findIndex.js'
import { propEq } from './propEq.js'

const list = [ { a : 1 }, { a : 2 }, { a : 3 } ]

test('happy', () => {
  expect(findIndex(propEq(2, 'a'), list)).toBe(1)
  expect(findIndex(propEq(1, 'a'))(list)).toBe(0)
  expect(findIndex(propEq(4, 'a'))(list)).toBe(-1)
})

---------------

findLast

findLast<T>(fn: (x: T) => boolean, list: T[]): T | undefined

It returns the last element of list satisfying the predicate function.

If there is no such element, then undefined is returned.

const predicate = x => R.type(x.foo) === 'Number'
const list = [{foo: 0}, {foo: 1}]

const result = R.findLast(predicate, list)
// => {foo: 1}

Try this R.findLast example in Rambda REPL

All TypeScript definitions
findLast<T>(fn: (x: T) => boolean, list: T[]): T | undefined;
findLast<T>(fn: (x: T) => boolean): (list: T[]) => T | undefined;
R.findLast source
export function findLast(predicate, list){
  if (arguments.length === 1) return _list => findLast(predicate, _list)

  let index = list.length

  while (--index >= 0){
    if (predicate(list[ index ])){
      return list[ index ]
    }
  }

  return undefined
}
Tests
import { findLast } from './findLast.js'

test('happy', () => {
  const result = findLast(x => x > 1, [ 1, 1, 1, 2, 3, 4, 1 ])
  expect(result).toBe(4)

  expect(findLast(x => x === 0, [ 0, 1, 1, 2, 3, 4, 1 ])).toBe(0)
})

test('with curry', () => {
  expect(findLast(x => x > 1)([ 1, 1, 1, 2, 3, 4, 1 ])).toBe(4)
})

const obj1 = { x : 100 }
const obj2 = { x : 200 }
const a = [ 11, 10, 9, 'cow', obj1, 8, 7, 100, 200, 300, obj2, 4, 3, 2, 1, 0 ]
const even = function (x){
  return x % 2 === 0
}
const gt100 = function (x){
  return x > 100
}
const isStr = function (x){
  return typeof x === 'string'
}
const xGt100 = function (o){
  return o && o.x > 100
}

test('ramda 1', () => {
  expect(findLast(even, a)).toBe(0)
  expect(findLast(gt100, a)).toBe(300)
  expect(findLast(isStr, a)).toBe('cow')
  expect(findLast(xGt100, a)).toEqual(obj2)
})

test('ramda 2', () => {
  expect(findLast(even, [ 'zing' ])).toBeUndefined()
})

test('ramda 3', () => {
  expect(findLast(even, [ 2, 3, 5 ])).toBe(2)
})

test('ramda 4', () => {
  expect(findLast(even, [])).toBeUndefined()
})

---------------

findLastIndex

findLastIndex<T>(predicate: (x: T) => boolean, list: T[]): number

It returns the index of the last element of list satisfying the predicate function.

If there is no such element, then -1 is returned.

const predicate = x => R.type(x.foo) === 'Number'
const list = [{foo: 0}, {foo: 1}]

const result = R.findLastIndex(predicate, list)
// => 1

Try this R.findLastIndex example in Rambda REPL

All TypeScript definitions
findLastIndex<T>(predicate: (x: T) => boolean, list: T[]): number;
findLastIndex<T>(predicate: (x: T) => boolean): (list: T[]) => number;
R.findLastIndex source
export function findLastIndex(fn, list){
  if (arguments.length === 1) return _list => findLastIndex(fn, _list)

  let index = list.length

  while (--index >= 0){
    if (fn(list[ index ])){
      return index
    }
  }

  return -1
}
Tests
import { findLastIndex } from './findLastIndex.js'

test('happy', () => {
  const result = findLastIndex(x => x > 1, [ 1, 1, 1, 2, 3, 4, 1 ])

  expect(result).toBe(5)

  expect(findLastIndex(x => x === 0, [ 0, 1, 1, 2, 3, 4, 1 ])).toBe(0)
})

test('with curry', () => {
  expect(findLastIndex(x => x > 1)([ 1, 1, 1, 2, 3, 4, 1 ])).toBe(5)
})

const obj1 = { x : 100 }
const obj2 = { x : 200 }
const a = [ 11, 10, 9, 'cow', obj1, 8, 7, 100, 200, 300, obj2, 4, 3, 2, 1, 0 ]
const even = function (x){
  return x % 2 === 0
}
const gt100 = function (x){
  return x > 100
}
const isStr = function (x){
  return typeof x === 'string'
}
const xGt100 = function (o){
  return o && o.x > 100
}

test('ramda 1', () => {
  expect(findLastIndex(even, a)).toBe(15)
  expect(findLastIndex(gt100, a)).toBe(9)
  expect(findLastIndex(isStr, a)).toBe(3)
  expect(findLastIndex(xGt100, a)).toBe(10)
})

test('ramda 2', () => {
  expect(findLastIndex(even, [ 'zing' ])).toBe(-1)
})

test('ramda 3', () => {
  expect(findLastIndex(even, [ 2, 3, 5 ])).toBe(0)
})

test('ramda 4', () => {
  expect(findLastIndex(even, [])).toBe(-1)
})

---------------

flatten

flatten<T>(list: any[]): T[]

It deeply flattens an array.

const result = R.flatten([
  1, 
  2, 
  [3, 30, [300]], 
  [4]
])
// => [ 1, 2, 3, 30, 300, 4 ]

Try this R.flatten example in Rambda REPL

All TypeScript definitions
flatten<T>(list: any[]): T[];
R.flatten source
import { isArray } from './_internals/isArray.js'

export function flatten(list, input){
  const willReturn = input === undefined ? [] : input

  for (let i = 0; i < list.length; i++){
    if (isArray(list[ i ])){
      flatten(list[ i ], willReturn)
    } else {
      willReturn.push(list[ i ])
    }
  }

  return willReturn
}
Tests
import { flatten } from './flatten.js'

test('happy', () => {
  expect(flatten([ 1, 2, 3, [ [ [ [ [ 4 ] ] ] ] ] ])).toEqual([ 1, 2, 3, 4 ])

  expect(flatten([ 1, [ 2, [ [ 3 ] ] ], [ 4 ] ])).toEqual([ 1, 2, 3, 4 ])

  expect(flatten([ 1, [ 2, [ [ [ 3 ] ] ] ], [ 4 ] ])).toEqual([ 1, 2, 3, 4 ])

  expect(flatten([ 1, 2, [ 3, 4 ], 5, [ 6, [ 7, 8, [ 9, [ 10, 11 ], 12 ] ] ] ])).toEqual([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ])
})

test('readme example', () => {
  const result = flatten([ 1, 2, [ 3, 30, [ 300 ] ], [ 4 ] ])
  expect(result).toEqual([ 1, 2, 3, 30, 300, 4 ])
})

---------------

flip

flip<T, U, TResult>(fn: (arg0: T, arg1: U) => TResult): (arg1: U, arg0?: T) => TResult

It returns function which calls fn with exchanged first and second argument.

💥 Rambda's flip will throw if the arity of the input function is greater or equal to 5.

const subtractFlip = R.flip(R.subtract)

const result = [
  subtractFlip(1,7),
  R.subtract(1, 6)
]  
// => [6, -6]

Try this R.flip example in Rambda REPL

All TypeScript definitions
flip<T, U, TResult>(fn: (arg0: T, arg1: U) => TResult): (arg1: U, arg0?: T) => TResult;
R.flip source
function flipFn(fn){
  return (...input) => {
    if (input.length === 1){
      return holder => fn(holder, input[ 0 ])
    } else if (input.length === 2){
      return fn(input[ 1 ], input[ 0 ])
    } else if (input.length === 3){
      return fn(
        input[ 1 ], input[ 0 ], input[ 2 ]
      )
    } else if (input.length === 4){
      return fn(
        input[ 1 ], input[ 0 ], input[ 2 ], input[ 3 ]
      )
    }

    throw new Error('R.flip doesn\'t work with arity > 4')
  }
}

export function flip(fn){
  return flipFn(fn)
}
Tests
import { flip } from './flip.js'
import { subtract } from './subtract.js'
import { update } from './update.js'

test('function with arity of 2', () => {
  const subtractFlipped = flip(subtract)

  expect(subtractFlipped(1)(7)).toBe(6)
  expect(subtractFlipped(1, 7)).toBe(6)
  expect(subtractFlipped(
    1, 7, 9
  )).toBe(6)
})

test('function with arity of 3', () => {
  const updateFlipped = flip(update)

  const result = updateFlipped(
    88, 0, [ 1, 2, 3 ]
  )
  const curriedResult = updateFlipped(88, 0)([ 1, 2, 3 ])
  const tripleCurriedResult = updateFlipped(88)(0)([ 1, 2, 3 ])
  expect(result).toEqual([ 88, 2, 3 ])
  expect(curriedResult).toEqual([ 88, 2, 3 ])
  expect(tripleCurriedResult).toEqual([ 88, 2, 3 ])
})

test('function with arity of 4', () => {
  const testFunction = (
    a, b, c, d
  ) => `${ a - b }==${ c - d }`
  const testFunctionFlipped = flip(testFunction)

  const result = testFunction(
    1, 2, 3, 4
  )
  const flippedResult = testFunctionFlipped(
    2, 1, 3, 4
  )
  expect(result).toEqual(flippedResult)
  expect(result).toBe('-1==-1')
})

test('function with arity of 5', () => {
  const testFunction = (
    a, b, c, d, e
  ) => `${ a - b }==${ c - d - e }`
  const testFunctionFlipped = flip(testFunction)

  expect(() =>
    testFunctionFlipped(
      1, 2, 3, 4, 5
    )).toThrowErrorMatchingInlineSnapshot('"R.flip doesn\'t work with arity > 4"')
})

---------------

forEach

forEach<T>(fn: Iterator<T, void>, list: T[]): T[]

It applies iterable function over all members of list and returns list.

💥 It works with objects, unlike Ramda.

const sideEffect = {}
const result = R.forEach(
  x => sideEffect[`foo${x}`] = x
)([1, 2])

sideEffect // => {foo1: 1, foo2: 2}
result // => [1, 2]

Try this R.forEach example in Rambda REPL

All TypeScript definitions
forEach<T>(fn: Iterator<T, void>, list: T[]): T[];
forEach<T>(fn: Iterator<T, void>): (list: T[]) => T[];
forEach<T>(fn: ObjectIterator<T, void>, list: Dictionary<T>): Dictionary<T>;
forEach<T, U>(fn: ObjectIterator<T, void>): (list: Dictionary<T>) => Dictionary<T>;
R.forEach source
import { isArray } from './_internals/isArray.js'
import { forEachObjIndexedFn } from './forEachObjIndexed.js'

export function forEach(fn, iterable){
  if (arguments.length === 1) return _list => forEach(fn, _list)
  if (iterable === undefined) return

  if (isArray(iterable)){
    let index = 0
    const len = iterable.length

    while (index < len){
      fn(iterable[ index ])
      index++
    }
  } else return forEachObjIndexedFn(fn, iterable)

  return iterable
}
Tests
import { forEach } from './forEach.js'
import { type } from './type.js'

test('happy', () => {
  const sideEffect = {}
  forEach(x => sideEffect[ `foo${ x }` ] = x + 10)([ 1, 2 ])

  expect(sideEffect).toEqual({
    foo1 : 11,
    foo2 : 12,
  })
})

test('iterate over object', () => {
  const obj = {
    a : 1,
    b : [ 1, 2 ],
    c : { d : 7 },
    f : 'foo',
  }
  const result = {}
  const returned = forEach((
    val, prop, inputObj
  ) => {
    expect(type(inputObj)).toBe('Object')
    result[ prop ] = `${ prop }-${ type(val) }`
  })(obj)

  const expected = {
    a : 'a-Number',
    b : 'b-Array',
    c : 'c-Object',
    f : 'f-String',
  }

  expect(result).toEqual(expected)
  expect(returned).toEqual(obj)
})

test('with empty list', () => {
  const list = []
  const result = forEach(x => x * x)(list)

  expect(result).toEqual(list)
})

test('with wrong input', () => {
  const list = undefined
  const result = forEach(x => x * x)(list)

  expect(result).toBeUndefined()
})

test('returns the input', () => {
  const list = [ 1, 2, 3 ]
  const result = forEach(x => x * x)(list)

  expect(result).toEqual(list)
})

---------------

forEachIndexed

forEachIndexed<T>(fn: IndexedIterator<T, void>, list: T[]): T[]
All TypeScript definitions
forEachIndexed<T>(fn: IndexedIterator<T, void>, list: T[]): T[];
forEachIndexed<T>(fn: IndexedIterator<T, void>): (list: T[]) => T[];
forEachIndexed<T>(fn: ObjectIterator<T, void>, list: Dictionary<T>): Dictionary<T>;
forEachIndexed<T, U>(fn: ObjectIterator<T, void>): (list: Dictionary<T>) => Dictionary<T>;
R.forEachIndexed source
import { mapIndexed } from './mapIndexed.js'

export function forEachIndexed(fn, iterable){
  if (arguments.length === 1){
    return _iterable => forEachIndexed(fn, _iterable)
  }

  mapIndexed(fn, iterable)

  return iterable
}
Tests
import { forEachIndexed } from './forEachIndexed.js'

const list = [ 1, 2, 3 ]
const iterator = (x, i) => {
  expect(x).toBeNumber()
  expect(i).toBeNumber()
}

test('happy', () => {
  const result = forEachIndexed(iterator, list)

  expect(result).toEqual(list)
})

test('curried', () => {
  const result = forEachIndexed(iterator)(list)

  expect(result).toEqual(list)
})

---------------

forEachObjIndexed

forEachObjIndexed<T>(fn: (value: T[keyof T], key: keyof T, obj: T) => void, obj: T): T
All TypeScript definitions
forEachObjIndexed<T>(fn: (value: T[keyof T], key: keyof T, obj: T) => void, obj: T): T;
forEachObjIndexed<T>(fn: (value: T[keyof T], key: keyof T, obj: T) => void): (obj: T) => T;
R.forEachObjIndexed source
import { keys } from './_internals/keys.js'

export function forEachObjIndexedFn(fn, obj){
  let index = 0
  const listKeys = keys(obj)
  const len = listKeys.length

  while (index < len){
    const key = listKeys[ index ]
    fn(
      obj[ key ], key, obj
    )
    index++
  }

  return obj
}

export function forEachObjIndexed(fn, list){
  if (arguments.length === 1) return _list => forEachObjIndexed(fn, _list)
  if (list === undefined) return

  return forEachObjIndexedFn(fn, list)
}

---------------

fromPairs

fromPairs<V>(listOfPairs: ([number, V])[]): { [index: number]: V }

It transforms a listOfPairs to an object.

const listOfPairs = [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', [ 3, 4 ] ] ]
const expected = {
  a : 1,
  b : 2,
  c : [ 3, 4 ],
}

const result = R.fromPairs(listOfPairs)
// => `result` is equal to `expected`

Try this R.fromPairs example in Rambda REPL

All TypeScript definitions
fromPairs<V>(listOfPairs: ([number, V])[]): { [index: number]: V };
fromPairs<V>(listOfPairs: ([string, V])[]): { [index: string]: V };
R.fromPairs source
export function fromPairs(listOfPairs){
  const toReturn = {}
  listOfPairs.forEach(([ prop, value ]) => toReturn[ prop ] = value)

  return toReturn
}
Tests
import { fromPairs } from './fromPairs.js'

const list = [
  [ 'a', 1 ],
  [ 'b', 2 ],
  [ 'c', [ 3, 4 ] ],
]
const expected = {
  a : 1,
  b : 2,
  c : [ 3, 4 ],
}

test('happy', () => {
  expect(fromPairs(list)).toEqual(expected)
})

---------------

getter

getter<T>(keyOrKeys: string | string[] | undefined): T

The set of methods R.setter, R.getter and R.reset allow different parts of your logic to access communicate indirectly via shared cache object.

Usually these methods show that you might need to refactor to classes. Still, they can be helpful meanwhile.

R.getter: It provides access to the cache object. If undefined is used as a key, this method will return the whole cache object. If string is passed, then it will return cache value for this key. If array of string is passed, then it assume that this is array of keys and it will return the corresponding cache values for these keys.

R.setter: It allows cache object's keys to be changed. You can either set individual key-value pairs with R.setter(key, value) or you pass directly object, which will be merged with the cache object.

R.reset: It resets the cache object.

R.setter('foo','bar')
R.setter('a', 1)
R.getter(['foo','a']) // => {foo: 'bar', a: 1}

R.setter('a', 2)
R.getter('a') // => 2
R.reset()
R.getter('a') // => undefined

Try this R.getter example in Rambda REPL

All TypeScript definitions
getter<T>(keyOrKeys: string | string[] | undefined): T;
R.getter source
import { mergeRight } from './mergeRight.js'
import { pick } from './pick.js'
import { type } from './type.js'

let holder = {}

/**
 * Pass string to get value
 * Pass array to get object of values
 * Pass undefined to get all data
 */
export function getter(key){
  const typeKey = type(key)

  if (typeKey === 'String') return holder[ key ]

  if (typeKey === 'Array') return pick(key, holder)

  return holder
}

export function setter(maybeKey, maybeValue){
  const typeKey = type(maybeKey)
  const typeValue = type(maybeValue)

  if (typeKey === 'String'){
    if (typeValue === 'Function'){
      return holder[ maybeKey ] = maybeValue(holder[ maybeKey ])
    }

    return holder[ maybeKey ] = maybeValue
  }

  if (typeKey !== 'Object') return

  holder = mergeRight(holder, maybeKey)
}

export function reset(){
  holder = {}
}
Tests
import { add } from './add.js'
import { getter, reset, setter } from './getter.js'

afterEach(() => {
  reset()
})

test('happy', () => {
  const key = 'foo'
  setter(key, 1)

  expect(getter(key)).toBe(1)
})

test('docs example', () => {
  setter('foo', 'bar')
  setter('a', 1)
  expect(getter([ 'foo', 'a' ])).toEqual({
    foo : 'bar',
    a   : 1,
  })

  setter('a', 2)
  expect(getter('a')).toBe(2)
  reset()
  expect(getter('a')).toBeUndefined()
})

test('when array is key in getter', () => {
  setter({
    a : 1,
    b : 2,
    c : 3,
  })

  expect(getter([ 'a', 'b' ])).toEqual({
    a : 1,
    b : 2,
  })
})

test('getter with undefined as key returns all', () => {
  const data = {
    a : 1,
    b : 2,
    c : 3,
  }

  setter(data)

  expect(getter()).toEqual(data)
})

test('function as setter value', () => {
  const data = {
    a : 1,
    b : 2,
    c : 3,
  }

  setter(data)
  setter('a', add(10))

  expect(getter()).toEqual({
    a : 11,
    b : 2,
    c : 3,
  })
})

test('setter fallbacks to undefined', () => {
  expect(setter()).toBeUndefined
})

---------------

glue

glue(input: string, glueString?: string): string

It transforms multiline string to single line by gluing together the separate lines with the glueString and removing the empty spaces. By default glueString is equal to single space, so if that is what you need, then you can just pass a single argument.

const result = R.glue(`
  foo
  bar
  baz
`)
// => 'foo bar baz'

Try this R.glue example in Rambda REPL

All TypeScript definitions
glue(input: string, glueString?: string): string;
R.glue source
export function glue(input, glueChar){
  return input
    .split('\n')
    .filter(x => x.trim().length > 0)
    .map(x => x.trim())
    .join(glueChar === undefined ? ' ' : glueChar)
}
Tests
import { glue } from './glue.js'

test('empty string as a glue', () => {
  const result = glue(`
    foo
    bar
    baz
  `,
  '')

  const expectedResult = 'foobarbaz'

  expect(result).toBe(expectedResult)
})

test('case 0', () => {
  const zero = 'node node_modules/jest'
  const first = '--runInBand'
  const last = '-- src/a.spec.js'
  const flag = false
  const result = glue(`
    ${ zero }
    ${ first }
    ${ flag ? '--env=node' : '' }
    ${ last }
  `)

  const expectedResult = `${ zero } ${ first } ${ last }`

  expect(result).toBe(expectedResult)
})

test('case 1', () => {
  const zero = 'node node_modules/jest'
  const first = '--runInBand'
  const last = '-- src/a.spec.js'
  const flag = true
  const result = glue(`
    ${ zero }
    ${ first }
    ${ flag ? '--env=node' : '' }
    ${ last }
  `)

  const expectedResult = `${ zero } ${ first } --env=node ${ last }`

  expect(result).toBe(expectedResult)
})

test('case 2', () => {
  const first = '--runInBand'
  const result = glue(`
    zero
    ${ first }
    last
  `)
  const expectedResult = `zero ${ first } last`

  expect(result).toBe(expectedResult)
})

test('case 3', () => {
  const result = glue(`
    foo
    bar
    baz
  `)

  const expectedResult = 'foo bar baz'

  expect(result).toBe(expectedResult)
})

test('with glue', () => {
  const result = glue(`
    foo
    bar
    baz
  `,
  '==')

  const expectedResult = 'foo==bar==baz'

  expect(result).toBe(expectedResult)
})

---------------

groupBy

groupBy<T, K extends string = string>(fn: (a: T) => K): (list: T[]) => Partial<Record<K, T[]>>

It splits list according to a provided groupFn function and returns an object.

const list = [ 'a', 'b', 'aa', 'bb' ]
const groupFn = x => x.length

const result = R.groupBy(groupFn, list)
// => { '1': ['a', 'b'], '2': ['aa', 'bb'] }

Try this R.groupBy example in Rambda REPL

All TypeScript definitions
groupBy<T, K extends string = string>(fn: (a: T) => K): (list: T[]) => Partial<Record<K, T[]>>;
groupBy<T, K extends string = string>(fn: (a: T) => K, list: T[]): Partial<Record<K, T[]>>;
R.groupBy source
export function groupBy(groupFn, list){
  if (arguments.length === 1) return _list => groupBy(groupFn, _list)

  const result = {}
  for (let i = 0; i < list.length; i++){
    const item = list[ i ]
    const key = groupFn(item)

    if (!result[ key ]){
      result[ key ] = []
    }

    result[ key ].push(item)
  }

  return result
}
Tests
import { groupBy } from './groupBy.js'
import { prop } from './prop.js'

test('groupBy', () => {
  const list = [
    {
      age  : 12,
      name : 'john',
    },
    {
      age  : 12,
      name : 'jack',
    },
    {
      age  : 24,
      name : 'mary',
    },
    {
      age  : 24,
      name : 'steve',
    },
  ]
  const expectedResult = {
    12 : [
      {
        age  : 12,
        name : 'john',
      },
      {
        age  : 12,
        name : 'jack',
      },
    ],
    24 : [
      {
        age  : 24,
        name : 'mary',
      },
      {
        age  : 24,
        name : 'steve',
      },
    ],
  }

  expect(groupBy(prop('age'))(list)).toEqual(expectedResult)
  expect(groupBy(prop('age'), list)).toEqual(expectedResult)
})

---------------

groupWith

groupWith<T>(compareFn: (x: T, y: T) => boolean): (input: T[]) => (T[])[]

It returns separated version of list or string input, where separation is done with equality compareFn function.

const isConsecutive = (x, y) => x === y
const list = [1, 2, 2, 1, 1, 2]

const result = R.groupWith(isConsecutive, list)
// => [[1], [2,2], [1,1], [2]]

Try this R.groupWith example in Rambda REPL

All TypeScript definitions
groupWith<T>(compareFn: (x: T, y: T) => boolean): (input: T[]) => (T[])[];
groupWith<T>(compareFn: (x: T, y: T) => boolean, input: T[]): (T[])[];
groupWith<T>(compareFn: (x: T, y: T) => boolean, input: string): string[];
R.groupWith source
import { cloneList } from './_internals/cloneList.js'
import { isArray } from './_internals/isArray.js'

export function groupWith(compareFn, list){
  if (!isArray(list)) throw new TypeError('list.reduce is not a function')

  const clone = cloneList(list)

  if (list.length === 1) return [ clone ]

  const toReturn = []
  let holder = []

  clone.reduce((
    prev, current, i
  ) => {
    if (i === 0) return current

    const okCompare = compareFn(prev, current)
    const holderIsEmpty = holder.length === 0
    const lastCall = i === list.length - 1

    if (okCompare){
      if (holderIsEmpty) holder.push(prev)
      holder.push(current)
      if (lastCall) toReturn.push(holder)

      return current
    }

    if (holderIsEmpty){
      toReturn.push([ prev ])
      if (lastCall) toReturn.push([ current ])

      return current
    }

    toReturn.push(holder)
    if (lastCall) toReturn.push([ current ])
    holder = []

    return current
  }, undefined)

  return toReturn
}
Tests
import { equals } from './equals.js'
import { groupWith } from './groupWith.js'

test('issue is fixed', () => {
  const result = groupWith(equals, [ 1, 2, 2, 3 ])
  const expected = [ [ 1 ], [ 2, 2 ], [ 3 ] ]
  expect(result).toEqual(expected)
})

test('long list', () => {
  const result = groupWith(equals,
    [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 21, 21, 1, 2 ])

  const expected = [
    [ 0 ],
    [ 1, 1 ],
    [ 2 ],
    [ 3 ],
    [ 5 ],
    [ 8 ],
    [ 13 ],
    [ 21, 21, 21 ],
    [ 1 ],
    [ 2 ],
  ]
  expect(result).toEqual(expected)
})

test('readme example', () => {
  const list = [ 4, 3, 6, 2, 2, 1 ]

  const result = groupWith((a, b) => a - b === 1, list)
  const expected = [ [ 4, 3 ], [ 6 ], [ 2 ], [ 2, 1 ] ]
  expect(result).toEqual(expected)
})

test('throw with string as input', () => {
  expect(() =>
    groupWith(equals, 'Mississippi')).toThrowErrorMatchingInlineSnapshot('"list.reduce is not a function"')
})

const isConsecutive = function (a, b){
  return a + 1 === b
}

test('fix coverage', () => {
  expect(groupWith(isConsecutive, [ 1, 2, 3, 0 ])).toEqual([ [ 1, 2, 3 ], [ 0 ] ])
})

test('from ramda 0', () => {
  expect(groupWith(equals, [])).toEqual([])
  expect(groupWith(isConsecutive, [])).toEqual([])
})

test('from ramda 1', () => {
  expect(groupWith(isConsecutive, [ 4, 3, 2, 1 ])).toEqual([
    [ 4 ],
    [ 3 ],
    [ 2 ],
    [ 1 ],
  ])
})

test('from ramda 2', () => {
  expect(groupWith(isConsecutive, [ 1, 2, 3, 4 ])).toEqual([ [ 1, 2, 3, 4 ] ])
})

test('from ramda 3', () => {
  expect(groupWith(isConsecutive, [ 1, 2, 2, 3 ])).toEqual([
    [ 1, 2 ],
    [ 2, 3 ],
  ])
  expect(groupWith(isConsecutive, [ 1, 2, 9, 3, 4 ])).toEqual([
    [ 1, 2 ],
    [ 9 ],
    [ 3, 4 ],
  ])
})

test('list with single item', () => {
  const result = groupWith(equals, [ 0 ])

  const expected = [ [ 0 ] ]
  expect(result).toEqual(expected)
})

---------------

gt

gt<T, U>(x: T, y: U): boolean
const result = [R.gt(2, 1), R.gt(2, 3)]
// => [true, false]

Try this R.gt example in Rambda REPL

All TypeScript definitions
gt<T, U>(x: T, y: U): boolean;
gt<T, U>(x: T): (y: U) => boolean;
R.gt source
export function gt(a, b){
  if (arguments.length === 1)
    return _b => gt(a, _b)

  return a > b
}

---------------

gte

gte<T, U>(x: T, y: U): boolean
const result = [R.gte(2, 1), R.gte(2, 2), R.gte(2, 3)]
// => [true, true, false]

Try this R.gte example in Rambda REPL

All TypeScript definitions
gte<T, U>(x: T, y: U): boolean;
gte<T, U>(x: T): (y: U) => boolean;
R.gte source
export function gte(a, b){
  if (arguments.length === 1)
    return _b => gte(a, _b)

  return a >= b
}

---------------

has

has<T>(prop: string, obj: T): boolean

It returns true if obj has property prop.

const obj = {a: 1}

const result = [
  R.has('a', Record<string, unknown>),
  R.has('b', Record<string, unknown>)
]
// => [true, false]

Try this R.has example in Rambda REPL

All TypeScript definitions
has<T>(prop: string, obj: T): boolean;
has(prop: string): <T>(obj: T) => boolean;
R.has source
export function has(prop, obj){
  if (arguments.length === 1) return _obj => has(prop, _obj)

  if (!obj) return false

  return obj.hasOwnProperty(prop)
}
Tests
import { has } from './has.js'

test('happy', () => {
  expect(has('a')({ a : 1 })).toBeTrue()
  expect(has('b', { a : 1 })).toBeFalse()
})

test('with non-object', () => {
  expect(has('a', undefined)).toBeFalse()
  expect(has('a', null)).toBeFalse()
  expect(has('a', true)).toBeFalse()
  expect(has('a', '')).toBeFalse()
  expect(has('a', /a/)).toBeFalse()
})

---------------

hasIn

hasIn(searchProperty: string): <T>(obj: T) => boolean
const result = R.hasIn('a', {a: 1})
// => true

Try this R.hasIn example in Rambda REPL

All TypeScript definitions
hasIn(searchProperty: string): <T>(obj: T) => boolean;
hasIn<T>(searchProperty: string, obj: T): boolean;
R.hasIn source
import { propFn } from './prop.js';

export function hasIn(searchProperty, obj) {
	if (arguments.length === 1) {
		return (_obj) => hasIn(searchProperty, _obj);
	}

	return propFn(searchProperty, obj) !== undefined;
}
Tests
import { hasIn as hasInRamda } from 'ramda'

import { hasIn } from './hasIn.js'

const fred = {
  age  : 23,
  name : 'Fred',
}
const anon = { age : 99 }

test('returns a function that checks the appropriate property', () => {
  const nm = hasIn('name')
  expect(typeof nm).toBe('function')
  expect(nm(fred)).toBe(true)
  expect(nm(anon)).toBe(false)
})

test('checks properties from the prototype chain', () => {
  function Person(){}
  Person.prototype.age = function (){}

  const bob = new Person()
  expect(hasIn('age', bob)).toBe(true)
})

test('works properly when called with two arguments', () => {
  expect(hasIn('name', fred)).toBe(true)
  expect(hasIn('name', anon)).toBe(false)
})

test('returns false when non-existent object', () => {
  expect(hasIn('name', null)).toBe(false)
  expect(hasIn('name', undefined)).toBe(false)
})

---------------

hasPath

hasPath<T>(
  path: string | string[],
  input: object
): boolean

It will return true, if input object has truthy path(calculated with R.path).

const path = 'a.b'
const pathAsArray = ['a', 'b']
const obj = {a: {b: []}}

const result = [
  R.hasPath(path, Record<string, unknown>),
  R.hasPath(pathAsArray, Record<string, unknown>),
  R.hasPath('a.c', Record<string, unknown>),
]
// => [true, true, false]

Try this R.hasPath example in Rambda REPL

All TypeScript definitions
hasPath<T>(
  path: string | string[],
  input: object
): boolean;
hasPath<T>(
  path: string | string[]
): (input: object) => boolean;
R.hasPath source
import { path } from './path.js'

export function hasPath(pathInput, obj){
  if (arguments.length === 1){
    return objHolder => hasPath(pathInput, objHolder)
  }

  return path(pathInput, obj) !== undefined
}
Tests
import { hasPath } from './hasPath.js'

test('when true', () => {
  const path = 'a.b'
  const obj = { a : { b : [] } }

  const result = hasPath(path)(obj)
  const expectedResult = true

  expect(result).toEqual(expectedResult)
})

test('when false', () => {
  const path = 'a.b'
  const obj = {}

  const result = hasPath(path, obj)
  const expectedResult = false

  expect(result).toEqual(expectedResult)
})

---------------

head

head(str: string): string

It returns the first element of list or string input. It returns undefined if array has length of 0.

const result = [
  R.head([1, 2, 3]),
  R.head('foo') 
]
// => [1, 'f']

Try this R.head example in Rambda REPL

All TypeScript definitions
head(str: string): string;
head(str: ''): undefined;
head(list: readonly[]): undefined;
head<T>(list: never[]): undefined;
head<T extends unknown[]>(array: T): FirstArrayElement<T>
head<T extends readonly unknown[]>(array: T): FirstArrayElement<T>
R.head source
export function head(listOrString){
  if (typeof listOrString === 'string') return listOrString[ 0 ] || ''

  return listOrString[ 0 ]
}
Tests
import { head } from './head.js'

test('head', () => {
  expect(head([ 'fi', 'fo', 'fum' ])).toBe('fi')
  expect(head([])).toBeUndefined()
  expect(head('foo')).toBe('f')
  expect(head('')).toBe('')
})

---------------

identical

identical<T>(x: T, y: T): boolean

It returns true if its arguments a and b are identical.

Otherwise, it returns false.

💥 Values are identical if they reference the same memory. NaN is identical to NaN; 0 and -0 are not identical.

const objA = {a: 1};
const objB = {a: 1};
R.identical(objA, objA); // => true
R.identical(objA, objB); // => false
R.identical(1, 1); // => true
R.identical(1, '1'); // => false
R.identical([], []); // => false
R.identical(0, -0); // => false
R.identical(NaN, NaN); // => true

Try this R.identical example in Rambda REPL

All TypeScript definitions
identical<T>(x: T, y: T): boolean;
identical<T>(x: T): (y: T) => boolean;
R.identical source
import { objectIs } from './_internals/objectIs.js'

export function identical(a, b){
  if (arguments.length === 1) return _b => identical(a, _b)

  return objectIs(a, b)
}
Tests
import { F, T } from '../rambda.js'
import { identical } from './identical.js'

test('r.F and R.T', () => {
  expect(F()).toBeFalse()
  expect(T()).toBeTrue()
})

test('identical', () => {
  const a = { a : 1 }
  const b = { a : 1 }
  const c = {
    a : 1,
    b : 2,
  }

  expect(identical(100)(100)).toBeTrue()
  expect(identical(100, '100')).toBeFalse()
  expect(identical('string', 'string')).toBeTrue()
  expect(identical([], [])).toBeFalse()
  expect(identical(a, a)).toBeTrue()
  expect(identical(a, b)).toBeFalse()
  expect(identical(a, c)).toBeFalse()
  expect(identical(undefined, undefined)).toBeTrue()
  expect(identical(null, undefined)).toBeFalse()
})

---------------

identity

identity<T>(input: T): T

It just passes back the supplied input argument.

💥 Logic

R.identity(7) // => 7

Try this R.identity example in Rambda REPL

All TypeScript definitions
identity<T>(input: T): T;
R.identity source
export function identity(x){
  return x
}
Tests
import { identity } from './identity.js'

test('happy', () => {
  expect(identity(7)).toBe(7)
  expect(identity(true)).toBeTrue()
  expect(identity({ a : 1 })).toEqual({ a : 1 })
})

---------------

ifElse

ifElse<T, TFiltered extends T, TOnTrueResult, TOnFalseResult>(
  pred: (a: T) => a is TFiltered,
  onTrue: (a: TFiltered) => TOnTrueResult,
  onFalse: (a: Exclude<T, TFiltered>) => TOnFalseResult,
): (a: T) => TOnTrueResult | TOnFalseResult

It expects condition, onTrue and onFalse functions as inputs and it returns a new function with example name of fn.

When fn`` is called with inputargument, it will return eitheronTrue(input)oronFalse(input)depending oncondition(input)` evaluation.

const fn = R.ifElse(
 x => x>10,
 x => x*2,
 x => x*10
)

const result = [ fn(8), fn(18) ]
// => [80, 36]

Try this R.ifElse example in Rambda REPL

All TypeScript definitions
ifElse<T, TFiltered extends T, TOnTrueResult, TOnFalseResult>(
  pred: (a: T) => a is TFiltered,
  onTrue: (a: TFiltered) => TOnTrueResult,
  onFalse: (a: Exclude<T, TFiltered>) => TOnFalseResult,
): (a: T) => TOnTrueResult | TOnFalseResult;
ifElse<TArgs extends any[], TOnTrueResult, TOnFalseResult>(fn: (...args: TArgs) => boolean, onTrue: (...args: TArgs) => TOnTrueResult, onFalse: (...args: TArgs) => TOnFalseResult): (...args: TArgs) => TOnTrueResult | TOnFalseResult;
R.ifElse source
import { curry } from './curry.js'

function ifElseFn(
  condition, onTrue, onFalse
){
  return (...input) => {
		const conditionResult =
      typeof condition === 'boolean' ? condition : condition(...input)
    if (Boolean(conditionResult) ){
      return onTrue(...input)
    }

    return onFalse(...input)
  }
}

export const ifElse = curry(ifElseFn)
Tests
import { always } from './always.js'
import { has } from './has.js'
import { identity } from './identity.js'
import { ifElse } from './ifElse.js'
import { prop } from './prop.js'
import * as R from 'ramda'

const condition = has('foo')
const v = function (a){
  return typeof a === 'number'
}
const t = function (a){
  return a + 1
}
const ifFn = x => prop('foo', x).length
const elseFn = () => false

test('happy', () => {
  const fn = ifElse(condition, ifFn)(elseFn)

  expect(fn({ foo : 'bar' })).toBe(3)
  expect(fn({ fo : 'bar' })).toBeFalse()
})

test('ramda spec', () => {
  const ifIsNumber = ifElse(v)
  expect(ifIsNumber(t, identity)(15)).toBe(16)
  expect(ifIsNumber(t, identity)('hello')).toBe('hello')
})

test('pass all arguments', () => {
  const identity = function (a){
    return a
  }
  const v = function (){
    return true
  }
  const onTrue = function (a, b){
    expect(a).toBe(123)
    expect(b).toBe('abc')
  }
  ifElse(
    v, onTrue, identity
  )(123, 'abc')
})

test('accept constant as condition', () => {
  const fn = ifElse(true)(always(true))(always(false))

  expect(fn()).toBeTrue()
})

test('accept constant as condition - case 2', () => {
  const fn = ifElse(
    false, always(true), always(false)
  )

  expect(fn()).toBeFalse()
})

test('curry 1', () => {
  const fn = ifElse(condition, ifFn)(elseFn)

  expect(fn({ foo : 'bar' })).toBe(3)
  expect(fn({ fo : 'bar' })).toBeFalse()
})

test('curry 2', () => {
  const fn = ifElse(condition)(ifFn)(elseFn)

  expect(fn({ foo : 'bar' })).toBe(3)
  expect(fn({ fo : 'bar' })).toBeFalse()
})

test('simple arity of 1', () => {
  const condition = x => x > 5
  const onTrue = x => x + 1
  const onFalse = x => x + 10
  const result = ifElse(
    condition, onTrue, onFalse
  )(1)
  expect(result).toBe(11)
})

test('simple arity of 2', () => {
  const condition = (x, y) => x + y > 5
  const onTrue = (x, y) => x + y + 1
  const onFalse = (x, y) => x + y + 10
  const result = ifElse(
    condition, onTrue, onFalse
  )(1, 10)
  expect(result).toBe(12)
})

test('bug 750', () => {
	const value = 34;

	let result = ifElse(
	R.identity,
	R.always('true'),
	R.always('false')
	)(value)
	expect(result).toBe('true')
})

---------------

ifElseAsync

ifElseAsync<T, U>(
  condition: (x: T) => Promise<boolean>, 
  onTrue: (x: T) => U, 
  onFalse: (x: T) => U, 
  ): (x: T) => Promise<U>

Asynchronous version of R.ifElse. Any of condition, ifFn and elseFn can be either asynchronous or synchronous function.

const condition = async x => {
  await R.delay(100)
  return x > 1
}
const ifFn = async x => {
  await R.delay(100)
  return x + 1
}
const elseFn = async x => {
  await R.delay(100)
  return x - 1
}

const result = await R.ifElseAsync(
  condition,
  ifFn,
  elseFn  
)(1)
// => 0

Try this R.ifElseAsync example in Rambda REPL

All TypeScript definitions
ifElseAsync<T, U>(
  condition: (x: T) => Promise<boolean>, 
  onTrue: (x: T) => U, 
  onFalse: (x: T) => U, 
  ): (x: T) => Promise<U>;
ifElseAsync<T, U>(
  condition: (x: T) => boolean, 
  onTrue: (x: T) => Promise<U>, 
  onFalse: (x: T) => Promise<U>, 
): (x: T) => Promise<U>;
ifElseAsync<T, U>(
  condition: (x: T) => Promise<boolean>, 
  onTrue: (x: T) => Promise<U>, 
  onFalse: (x: T) => Promise<U>, 
): (x: T) => Promise<U>;
ifElseAsync<T, K, U>(
  condition: (x: T, y: K) => Promise<boolean>, 
  onTrue: (x: T, y: K) => U, 
  onFalse: (x: T, y: K) => U, 
): (x: T, y: K) => Promise<U>;
ifElseAsync<T, K, U>(
  condition: (x: T, y: K) => boolean, 
  onTrue: (x: T, y: K) => Promise<U>, 
  onFalse: (x: T, y: K) => Promise<U>, 
): (x: T, y: K) => Promise<U>;
ifElseAsync<T, K, U>(
  condition: (x: T, y: K) => Promise<boolean>, 
  onTrue: (x: T, y: K) => Promise<U>, 
  onFalse: (x: T, y: K) => Promise<U>, 
): (x: T, y: K) => Promise<U>;
R.ifElseAsync source
function createThenable(fn){
  return async function (...input){
    return fn(...input)
  }
}

export function ifElseAsync(
  condition, ifFn, elseFn
){
  return (...inputs) =>
    new Promise((resolve, reject) => {
      const conditionPromise = createThenable(condition)
      const ifFnPromise = createThenable(ifFn)
      const elseFnPromise = createThenable(elseFn)

      conditionPromise(...inputs)
        .then(conditionResult => {
          const promised =
            conditionResult === true ? ifFnPromise : elseFnPromise

          promised(...inputs)
            .then(resolve)
            .catch(reject)
        })
        .catch(reject)
    })
}
Tests
import { delay } from './delay.js'
import { ifElseAsync } from './ifElseAsync.js'

test('arity of 1 - condition is async', async () => {
  const condition = async x => {
    await delay(100)

    return x > 4
  }
  const whenTrue = x => x + 1
  const whenFalse = x => x + 10
  const fn = ifElseAsync(
    condition, whenTrue, whenFalse
  )
  const result = await Promise.all([ fn(5), fn(1) ])
  expect(result).toEqual([ 6, 11 ])
})

test('arity of 1 - condition is sync', async () => {
  const condition = x => x > 4
  const whenTrue = async x => {
    await delay(100)

    return x + 1
  }
  const whenFalse = async x => {
    await delay(100)

    return x + 10
  }
  const fn = ifElseAsync(
    condition, whenTrue, whenFalse
  )
  const result = await Promise.all([ fn(5), fn(1) ])
  expect(result).toEqual([ 6, 11 ])
})

test('arity of 1 - all inputs are async', async () => {
  const condition = async x => {
    await delay(100)

    return x > 4
  }
  const whenTrue = async x => {
    await delay(100)

    return x + 1
  }
  const whenFalse = async x => {
    await delay(100)

    return x + 10
  }
  const fn = ifElseAsync(
    condition, whenTrue, whenFalse
  )
  const result = await Promise.all([ fn(5), fn(1) ])
  expect(result).toEqual([ 6, 11 ])
})

test('arity of 2 - condition is async', async () => {
  const condition = async (x, y) => {
    await delay(100)

    return x + y > 4
  }
  const whenTrue = (x, y) => x + y + 1
  const whenFalse = (x, y) => x + y + 10
  const fn = ifElseAsync(
    condition, whenTrue, whenFalse
  )
  const result = await Promise.all([ fn(14, 20), fn(1, 3) ])
  expect(result).toEqual([ 35, 14 ])
})

test('arity of 2 - condition is sync', async () => {
  const condition = (x, y) => x + y > 4
  const whenTrue = async (x, y) => {
    await delay(100)

    return x + y + 1
  }
  const whenFalse = async (x, y) => {
    await delay(100)

    return x + y + 10
  }
  const fn = ifElseAsync(
    condition, whenTrue, whenFalse
  )
  const result = await Promise.all([ fn(14, 20), fn(1, 3) ])
  expect(result).toEqual([ 35, 14 ])
})

test('arity of 2 - all inputs are async', async () => {
  const condition = async (x, y) => {
    await delay(100)

    return x + y > 4
  }
  const whenTrue = async (x, y) => {
    await delay(100)

    return x + y + 1
  }
  const whenFalse = async (x, y) => {
    await delay(100)

    return x + y + 10
  }
  const fn = ifElseAsync(
    condition, whenTrue, whenFalse
  )
  const result = await Promise.all([ fn(14, 20), fn(1, 3) ])
  expect(result).toEqual([ 35, 14 ])
})

---------------

inc

inc(x: number): number

It increments a number.

R.inc(1) // => 2

Try this R.inc example in Rambda REPL

All TypeScript definitions
inc(x: number): number;
R.inc source
export const inc = x => x + 1
Tests
import { inc } from './inc.js'

test('happy', () => {
  expect(inc(1)).toBe(2)
})

---------------

includes

includes<T extends string>(valueToFind: T, input: string): boolean

If input is string, then this method work as native String.includes.

If input is array, then R.equals is used to define if valueToFind belongs to the list.

const result = [
  R.includes('oo', 'foo'),
  R.includes({a: 1}, [{a: 1}])
]
// => [true, true ]

Try this R.includes example in Rambda REPL

All TypeScript definitions
includes<T extends string>(valueToFind: T, input: string): boolean;
includes<T extends string>(valueToFind: T): (input: string) => boolean;
includes<T>(valueToFind: T, input: T[]): boolean;
includes<T>(valueToFind: T): (input: T[]) => boolean;
R.includes source
import { isArray } from './_internals/isArray.js'
import { _indexOf } from './equals.js'

export function includes(valueToFind, iterable){
  if (arguments.length === 1)
    return _iterable => includes(valueToFind, _iterable)
  if (typeof iterable === 'string'){
    return iterable.includes(valueToFind)
  }
  if (!iterable){
    throw new TypeError(`Cannot read property \'indexOf\' of ${ iterable }`)
  }
  if (!isArray(iterable)) return false

  return _indexOf(valueToFind, iterable) > -1
}
Tests
import { includes as includesRamda } from 'ramda'

import { includes } from './includes.js'

test('with string as iterable', () => {
  const str = 'foo bar'

  expect(includes('bar')(str)).toBeTrue()
  expect(includesRamda('bar')(str)).toBeTrue()
  expect(includes('never', str)).toBeFalse()
  expect(includesRamda('never', str)).toBeFalse()
})

test('with array as iterable', () => {
  const arr = [ 1, 2, 3 ]

  expect(includes(2)(arr)).toBeTrue()
  expect(includesRamda(2)(arr)).toBeTrue()

  expect(includes(4, arr)).toBeFalse()
  expect(includesRamda(4, arr)).toBeFalse()
})

test('with list of objects as iterable', () => {
  const arr = [ { a : 1 }, { b : 2 }, { c : 3 } ]

  expect(includes({ c : 3 }, arr)).toBeTrue()
  expect(includesRamda({ c : 3 }, arr)).toBeTrue()
})

test('with NaN', () => {
  const result = includes(NaN, [ NaN ])
  const ramdaResult = includesRamda(NaN, [ NaN ])
  expect(result).toBeTrue()
  expect(ramdaResult).toBeTrue()
})

test('with wrong input that does not throw', () => {
  const result = includes(1, /foo/g)
  const ramdaResult = includesRamda(1, /foo/g)
  expect(result).toBeFalse()
  expect(ramdaResult).toBeFalse()
})

test('throws on wrong input - match ramda behaviour', () => {
  expect(() => includes(2, null)).toThrowWithMessage(TypeError,
    'Cannot read property \'indexOf\' of null')
  expect(() => includesRamda(2, null)).toThrowWithMessage(TypeError,
    'Cannot read properties of null (reading \'indexOf\')')
  expect(() => includes(2, undefined)).toThrowWithMessage(TypeError,
    'Cannot read property \'indexOf\' of undefined')
  expect(() => includesRamda(2, undefined)).toThrowWithMessage(TypeError,
    'Cannot read properties of undefined (reading \'indexOf\')')
})

---------------

indexBy

indexBy<T, K extends string | number = string>(condition: (key: T) => K, list: T[]): { [key in K]: T }

It generates object with properties provided by condition and values provided by list array.

If condition is a function, then all list members are passed through it.

If condition is a string, then all list members are passed through R.path(condition).

const list = [ {id: 10}, {id: 20} ]

const withFunction = R.indexBy(
  x => x.id,
  list
)
const withString = R.indexBy(
  'id',
  list
)
const result = [
  withFunction, 
  R.equals(withFunction, withString)
]
// => [ { 10: {id: 10}, 20: {id: 20} }, true ]

Try this R.indexBy example in Rambda REPL

All TypeScript definitions
indexBy<T, K extends string | number = string>(condition: (key: T) => K, list: T[]): { [key in K]: T };
indexBy<T, K extends string | number | undefined = string>(condition: (key: T) => K, list: T[]): { [key in NonNullable<K>]?: T };
indexBy<T, K extends string | number = string>(condition: (key: T) => K): (list: T[]) => { [key in K]: T };
indexBy<T, K extends string | number | undefined = string>(condition: (key: T) => K | undefined): (list: T[]) => { [key in NonNullable<K>]?: T };
indexBy<T>(condition: string, list: T[]): { [key: string]: T };
indexBy<T>(condition: string): (list: T[]) => { [key: string]: T };
R.indexBy source
import { path } from './path.js'

function indexByPath(pathInput, list){
  const toReturn = {}
  for (let i = 0; i < list.length; i++){
    const item = list[ i ]
    toReturn[ path(pathInput, item) ] = item
  }

  return toReturn
}

export function indexBy(condition, list){
  if (arguments.length === 1){
    return _list => indexBy(condition, _list)
  }

  if (typeof condition === 'string'){
    return indexByPath(condition, list)
  }

  const toReturn = {}
  for (let i = 0; i < list.length; i++){
    const item = list[ i ]
    toReturn[ condition(item) ] = item
  }

  return toReturn
}
Tests
import { indexBy } from './indexBy.js'
import { prop } from './prop.js'

test('happy', () => {
  const list = [
    { id : 1 },
    {
      id : 1,
      a  : 2,
    },
    { id : 2 },
    { id : 10 },
    { id : 'a' },
  ]

  expect(indexBy(prop('id'))(list)).toEqual({
    1 : {
      id : 1,
      a  : 2,
    },
    2  : { id : 2 },
    10 : { id : 10 },
    a  : { id : 'a' },
  })
})

test('with string as condition', () => {
  const list = [ { id : 1 }, { id : 2 }, { id : 10 }, { id : 'a' } ]
  const standardResult = indexBy(obj => obj.id, list)
  const suggestionResult = indexBy('id', list)

  expect(standardResult).toEqual(suggestionResult)
})

test('with string - bad path', () => {
  const list = [
    {
      a : {
        b : 1,
        c : 2,
      },
    },
    { a : { c : 4 } },
    {},
    {
      a : {
        b : 10,
        c : 20,
      },
    },
  ]

  const result = indexBy('a.b', list)
  const expected = {
    1 : {
      a : {
        b : 1,
        c : 2,
      },
    },
    10 : {
      a : {
        b : 10,
        c : 20,
      },
    },
    undefined : {},
  }

  expect(result).toEqual(expected)
})

---------------

indexOf

indexOf<T>(valueToFind: T, list: T[]): number

It returns the index of the first element of list equals to valueToFind.

If there is no such element, it returns -1.

💥 It uses R.equals for list of objects/arrays or native indexOf for any other case.

const list = [0, 1, 2, 3]

const result = [
  R.indexOf(2, list),
  R.indexOf(0, list)
]
// => [2, -1]

Try this R.indexOf example in Rambda REPL

All TypeScript definitions
indexOf<T>(valueToFind: T, list: T[]): number;
indexOf<T>(valueToFind: T): (list: T[]) => number;
R.indexOf source
import { _indexOf } from './equals.js'

export function indexOf(valueToFind, list){
  if (arguments.length === 1){
    return _list => _indexOf(valueToFind, _list)
  }

  return _indexOf(valueToFind, list)
}
Tests
import { indexOf as indexOfRamda } from 'ramda'

import { compareCombinations } from './_internals/testUtils.js'
import { indexOf } from './indexOf.js'

test('with NaN', () => {
  expect(indexOf(NaN, [ NaN ])).toBe(0)
})

test('will throw with bad input', () => {
  expect(indexOfRamda([], true)).toBe(-1)
  expect(() => indexOf([], true)).toThrow()
})

test('without list of objects - no R.equals', () => {
  expect(indexOf(3, [ 1, 2, 3, 4 ])).toBe(2)
  expect(indexOf(10)([ 1, 2, 3, 4 ])).toBe(-1)
})

test('list of objects uses R.equals', () => {
  const listOfObjects = [ { a : 1 }, { b : 2 }, { c : 3 } ]
  expect(indexOf({ c : 4 }, listOfObjects)).toBe(-1)
  expect(indexOf({ c : 3 }, listOfObjects)).toBe(2)
})

test('list of arrays uses R.equals', () => {
  const listOfLists = [ [ 1 ], [ 2, 3 ], [ 2, 3, 4 ], [ 2, 3 ], [ 1 ], [] ]
  expect(indexOf([], listOfLists)).toBe(5)
  expect(indexOf([ 1 ], listOfLists)).toBe(0)
  expect(indexOf([ 2, 3, 4 ], listOfLists)).toBe(2)
  expect(indexOf([ 2, 3, 5 ], listOfLists)).toBe(-1)
})

test('with string as iterable', () => {
  expect(() => indexOf('a', 'abc')).toThrowWithMessage(Error,
    'Cannot read property \'indexOf\' of abc')
  expect(indexOfRamda('a', 'abc')).toBe(0)
})

export const possibleTargets = [
  x => x > 2,
  /foo/,
  'foo',
  { a : 1 },
  true,
  3,
  null,
  /bar/g,
  NaN,
  undefined,
  4,
  [],
  [ [] ],
  [ [ 1 ], [ 2 ] ],
  { a : 1 },
  { a : 2 },
  Promise.resolve(1),
]

export const possibleIterables = [
  [
    1,
    2,
    new Boolean(true),
    false,
    true,
    new String('foo'),
    new Number(3),
    null,
    undefined,
  ],
  [ /foo/g, /bar/, /bar/g, NaN ],
  [ 1, 2, 3 ],
  [ 1, [ [], [] ] ],
  [ { a : 3 }, { a : 2 }, { a : 1 } ],
  {},
  null,
  undefined,
  true,
  'foo',
]

describe('brute force', () => {
  compareCombinations({
    fn          : indexOf,
    fnRamda     : indexOfRamda,
    firstInput  : possibleTargets,
    secondInput : possibleIterables,
    callback    : errorsCounters => {
      expect(errorsCounters).toMatchInlineSnapshot(`
        {
          "ERRORS_MESSAGE_MISMATCH": 0,
          "ERRORS_TYPE_MISMATCH": 34,
          "RESULTS_MISMATCH": 0,
          "SHOULD_NOT_THROW": 51,
          "SHOULD_THROW": 0,
          "TOTAL_TESTS": 170,
        }
      `)
    },
  })
})

---------------

init

init<T extends unknown[]>(input: T): T extends readonly [...infer U, any] ? U : [...T]

It returns all but the last element of list or string input.

const result = [
  R.init([1, 2, 3]) , 
  R.init('foo')  // => 'fo'
]
// => [[1, 2], 'fo']

Try this R.init example in Rambda REPL

All TypeScript definitions
init<T extends unknown[]>(input: T): T extends readonly [...infer U, any] ? U : [...T];
init(input: string): string;
R.init source
import baseSlice from './_internals/baseSlice.js'

export function init(listOrString){
  if (typeof listOrString === 'string') return listOrString.slice(0, -1)

  return listOrString.length ?
    baseSlice(
      listOrString, 0, -1
    ) :
    []
}
Tests
import { init } from './init.js'

test('with array', () => {
  expect(init([ 1, 2, 3 ])).toEqual([ 1, 2 ])
  expect(init([ 1, 2 ])).toEqual([ 1 ])
  expect(init([ 1 ])).toEqual([])
  expect(init([])).toEqual([])
  expect(init([])).toEqual([])
  expect(init([ 1 ])).toEqual([])
})

test('with string', () => {
  expect(init('foo')).toBe('fo')
  expect(init('f')).toBe('')
  expect(init('')).toBe('')
})

---------------

innerJoin

innerJoin<T1, T2>(
  pred: (a: T1, b: T2) => boolean,
): (list1: T1[], list2: T2[]) => T1[]

It returns a new list by applying a predicate function to all elements of list1 and list2 and keeping only these elements where predicate returns true.

const list1 = [1, 2, 3, 4, 5]
const list2 = [4, 5, 6]
const predicate = (x, y) => x >= y
const result = R.innerJoin(predicate, list1, list2)
// => [4, 5]

Try this R.innerJoin example in Rambda REPL

All TypeScript definitions
innerJoin<T1, T2>(
  pred: (a: T1, b: T2) => boolean,
): (list1: T1[], list2: T2[]) => T1[];
innerJoin<T1, T2>(
  pred: (a: T1, b: T2) => boolean,
  list1: T1[],
): (list2: T2[]) => T1[];
innerJoin<T1, T2>(pred: (a: T1, b: T2) => boolean, list1: T1[], list2: T2[]): T1[];
R.innerJoin source
import { curry } from './curry.js'

function _includesWith(
  pred, x, list
){
  let idx = 0
  const len = list.length

  while (idx < len){
    if (pred(x, list[ idx ]))
      return true

    idx += 1
  }

  return false
}
function _filter(fn, list){
  let idx = 0
  const len = list.length
  const result = []

  while (idx < len){
    if (fn(list[ idx ]))
      result[ result.length ] = list[ idx ]

    idx += 1
  }

  return result
}

export function innerJoinFn(
  pred, xs, ys
){
  return _filter(x => _includesWith(
    pred, x, ys
  ), xs)
}

export const innerJoin = curry(innerJoinFn)
Tests
import { innerJoin } from './innerJoin.js'

const a = {
  id: 1,
  name: 'a',
}
const b = {
  id: 2,
  name: 'b',
}
const c = {
  id: 3,
  name: 'c',
}
const f = innerJoin((r, id) => r.id === id)

test('only returns elements from the first list', () => {
  expect(f([a, b, c], [])).toEqual([])
  expect(f([a, b, c], [1])).toEqual([a])
  expect(f([a, b, c], [1, 2])).toEqual([a, b])
  expect(f([a, b, c], [1, 2, 3])).toEqual([a, b, c])
  expect(f([a, b, c], [1, 2, 3, 4])).toEqual([a, b, c])
})

test('does not remove duplicates', () => {
  expect(f([a, a, a], [1, 2, 3])).toEqual([a, a, a])
  expect(f([a, b, c], [1, 1, 1])).toEqual([a])
})

test('readme example', () => {
  const list1 = [1, 2, 3, 4, 5]
  const list2 = [4, 5, 6]
  const predicate = (x, y) => x >= y
  const result = innerJoin(predicate, list1, list2)
  expect(result).toEqual([4, 5])
})

---------------

insert

insert(index: number): <T>(itemToInsert: T, list: T[]) => T[]
const list = ['a', 'b', 'c', 'd', 'e'];
const result = R.insert(2, 'x', list);
// => ['a', 'b', 'x', 'c', 'd', 'e']

Try this R.insert example in Rambda REPL

All TypeScript definitions
insert(index: number): <T>(itemToInsert: T, list: T[]) => T[];
insert<T>(index: number, itemToInsert: T): (list: T[]) => T[];
insert<T>(index: number, itemToInsert: T, list: T[]): T[];
R.insert source
import { curry } from './curry.js'

export function insertFn(indexToInsert, valueToInsert, array) {
  return [
    ...array.slice(0, indexToInsert),
    valueToInsert,
    ...array.slice(indexToInsert),
  ]
}

export const insert = curry(insertFn)
Tests
import { insert } from './insert';

it('inserts an element into the given list', () => {
	const list = ['a', 'b', 'c', 'd', 'e'];
	expect(insert(2, 'x', list)).toEqual(['a', 'b', 'x', 'c', 'd', 'e']);
});

it('inserts another list as an element', () => {
	const list = ['a', 'b', 'c', 'd', 'e'];
	expect(insert(2, ['s', 't'], list)).toEqual([
		'a',
		'b',
		['s', 't'],
		'c',
		'd',
		'e',
	]);
});

it('appends to the end of the list if the index is too large', () => {
	const list = ['a', 'b', 'c', 'd', 'e'];
	expect(insert(8, 'z', list)).toEqual(['a', 'b', 'c', 'd', 'e', 'z']);
});

---------------

insertAll

insertAll(index: number): <T>(itemsToInsert: T[], list: T[]) => T[]
const list = ['a', 'b', 'c', 'd', 'e'];
const result = R.insertAll(2, ['x', 'y', 'z'], list);
// => ['a', 'b', 'x', 'y', 'z', 'c', 'd', 'e']

Try this R.insertAll example in Rambda REPL

All TypeScript definitions
insertAll(index: number): <T>(itemsToInsert: T[], list: T[]) => T[];
insertAll<T>(index: number, itemsToInsert: T[]): (list: T[]) => T[];
insertAll<T>(index: number, itemsToInsert: T[], list: T[]): T[];
R.insertAll source
import { curry } from './curry.js';

export function insertAllFn(index, listToInsert, list) {
	return [...list.slice(0, index), ...listToInsert, ...list.slice(index)];
}

export const insertAll = curry(insertAllFn);
Tests
import { insertAll } from './insertAll';

it('inserts a list of elements into the given list', () => {
	const list = ['a', 'b', 'c', 'd', 'e'];
	expect(insertAll(2, ['x', 'y', 'z'], list)).toEqual([
		'a',
		'b',
		'x',
		'y',
		'z',
		'c',
		'd',
		'e',
	]);
});

it('appends to the end of the list if the index is too large', () => {
	const list = ['a', 'b', 'c', 'd', 'e'];
	expect(insertAll(8, ['p', 'q', 'r'], list)).toEqual([
		'a',
		'b',
		'c',
		'd',
		'e',
		'p',
		'q',
		'r',
	]);
});

---------------

interpolate

interpolate(inputWithTags: string, templateArguments: object): string

It generates a new string from inputWithTags by replacing all {{x}} occurrences with values provided by templateArguments.

const inputWithTags = 'foo is {{bar}} even {{a}} more'
const templateArguments = {"bar":"BAR", a: 1}

const result = R.interpolate(inputWithTags, templateArguments)
const expected = 'foo is BAR even 1 more'
// => `result` is equal to `expected`

Try this R.interpolate example in Rambda REPL

All TypeScript definitions
interpolate(inputWithTags: string, templateArguments: object): string;
interpolate(inputWithTags: string): (templateArguments: object) => string;
R.interpolate source
const getOccurrences = input => input.match(/{{\s*.+?\s*}}/g)

const getOccurrenceProp = occurrence =>
  occurrence.replace(/{{\s*|\s*}}/g, '')

const replace = ({ inputHolder, prop, replacer }) => {
  const regexBase = `{{${ prop }}}`
  const regex = new RegExp(regexBase, 'g')

  return inputHolder.replace(regex, replacer)
}

export function interpolate(input, templateInput){
  if (arguments.length === 1){
    return _templateInput => interpolate(input, _templateInput)
  }

  const occurrences = getOccurrences(input)
  if (occurrences === null) return input
  let inputHolder = input

  for (const occurrence of occurrences){
    const prop = getOccurrenceProp(occurrence)

    inputHolder = replace({
      inputHolder,
      prop,
      replacer : templateInput[ prop ],
    })
  }

  return inputHolder
}
Tests
import { interpolate } from './interpolate.js'

test('within bracets', () => {
  const input = 'foo is { {{bar}} } even {{a}} more'
  const templateInput = {
    bar : 'BAR',
    a   : 1,
  }

  const result = interpolate(input, templateInput)
  const expectedResult = 'foo is { BAR } even 1 more'

  expect(result).toEqual(expectedResult)
})

test('happy', () => {
  const input = 'foo is {{bar}} even {{a}} more'
  const templateInput = {
    bar : 'BAR',
    a   : 1,
  }

  const result = interpolate(input, templateInput)
  const expectedResult = 'foo is BAR even 1 more'

  expect(result).toEqual(expectedResult)
})

test('no interpolation + curry', () => {
  const input = 'foo is bar even more'
  const templateInput = { bar : 'BAR' }

  const result = interpolate(input)(templateInput)
  const expectedResult = 'foo is bar even more'

  expect(result).toEqual(expectedResult)
})

test('with missing template input', () => {
  const input = 'foo is {{bar}} even {{a}} more'
  const templateInput = {
    baz : 'BAR',
    a   : 1,
  }

  const result = interpolate(input, templateInput)
  const expectedResult = 'foo is undefined even 1 more'

  expect(result).toEqual(expectedResult)
})

test('with arbitrary expression', () => {
  const input = '1 + 2 = {{ 1 + 2 }}'
  const templateInput = {}

  const result = interpolate(input, templateInput)

  expect(result).toEqual(input)
})

---------------

intersection

intersection<T>(listA: T[], listB: T[]): T[]

It loops through listA and listB and returns the intersection of the two according to R.equals.

💥 There is slight difference between Rambda and Ramda implementation. Ramda.intersection(['a', 'b', 'c'], ['c', 'b']) result is "[ 'c', 'b' ]", but Rambda result is "[ 'b', 'c' ]".

const listA = [ { id : 1 }, { id : 2 }, { id : 3 }, { id : 4 } ]
const listB = [ { id : 3 }, { id : 4 }, { id : 5 }, { id : 6 } ]

const result = R.intersection(listA, listB)
// => [{ id : 3 }, { id : 4 }]

Try this R.intersection example in Rambda REPL

All TypeScript definitions
intersection<T>(listA: T[], listB: T[]): T[];
intersection<T>(listA: T[]): (listB: T[]) => T[];
R.intersection source
import { filter } from './filter.js'
import { includes } from './includes.js'

export function intersection(listA, listB){
  if (arguments.length === 1) return _list => intersection(listA, _list)

  return filter(x => includes(x, listA), listB)
}
Tests
import { intersection as intersectionRamda } from 'ramda'

import { intersection } from './intersection.js'

test('intersection', () => {
  const list1 = [ 1, 2, 3, 4 ]
  const list2 = [ 3, 4, 5, 6 ]
  expect(intersection(list1)(list2)).toEqual([ 3, 4 ])

  expect(intersection([], [])).toEqual([])
})

test('intersection with objects', () => {
  const list1 = [ { id : 1 }, { id : 2 }, { id : 3 }, { id : 4 } ]
  const list2 = [ { id : 3 }, { id : 4 }, { id : 5 }, { id : 6 } ]
  expect(intersection(list1)(list2)).toEqual([ { id : 3 }, { id : 4 } ])
})

test('order is the same as in Ramda', () => {
  const list = [ 'a', 'b', 'c', 'd' ]

  expect(intersectionRamda(list, [ 'b', 'c' ])).toEqual([ 'b', 'c' ])
  expect(intersection(list, [ 'b', 'c' ])).toEqual([ 'b', 'c' ])

  expect(intersection(list, [ 'c', 'b' ])).toEqual([ 'c', 'b' ])
  expect(intersectionRamda(list, [ 'c', 'b' ])).toEqual([ 'c', 'b' ])
})

---------------

intersperse

intersperse<T>(separator: T, list: T[]): T[]

It adds a separator between members of list.

const list = [ 0, 1, 2, 3 ]
const separator = '|'
const result = intersperse(separator, list)
// => [0, '|', 1, '|', 2, '|', 3]

Try this R.intersperse example in Rambda REPL

All TypeScript definitions
intersperse<T>(separator: T, list: T[]): T[];
intersperse<T>(separator: T): (list: T[]) => T[];
R.intersperse source
export function intersperse(separator, list){
  if (arguments.length === 1) return _list => intersperse(separator, _list)

  let index = -1
  const len = list.length
  const willReturn = []

  while (++index < len){
    if (index === len - 1){
      willReturn.push(list[ index ])
    } else {
      willReturn.push(list[ index ], separator)
    }
  }

  return willReturn
}
Tests
import { intersperse } from './intersperse.js'

test('intersperse', () => {
  const list = [ { id : 1 }, { id : 2 }, { id : 10 }, { id : 'a' } ]
  expect(intersperse('!', list)).toEqual([
    { id : 1 },
    '!',
    { id : 2 },
    '!',
    { id : 10 },
    '!',
    { id : 'a' },
  ])

  expect(intersperse('!')([])).toEqual([])
})

---------------

is

is<C extends () => any>(targetPrototype: C, val: any): val is ReturnType<C>

It returns true if x is instance of targetPrototype.

const result = [
  R.is(String, 'foo'),  
  R.is(Array, 1)
]
// => [true, false]

Try this R.is example in Rambda REPL

All TypeScript definitions
is<C extends () => any>(targetPrototype: C, val: any): val is ReturnType<C>;
is<C extends new () => any>(targetPrototype: C, val: any): val is InstanceType<C>;
is<C extends () => any>(targetPrototype: C): (val: any) => val is ReturnType<C>;
is<C extends new () => any>(targetPrototype: C): (val: any) => val is InstanceType<C>;
R.is source
export function is(targetPrototype, x){
  if (arguments.length === 1) return _x => is(targetPrototype, _x)

  return (
    x != null && x.constructor === targetPrototype ||
    x instanceof targetPrototype
  )
}
Tests
import { is } from './is.js'

test('works with built-in types', () => {
  expect(is(Array, undefined)).toBeFalse()
  expect(is(Array)([])).toBeTrue()
  expect(is(Boolean, new Boolean(false))).toBeTrue()
  expect(is(Date, new Date())).toBeTrue()
  expect(is(Function, () => {})).toBeTrue()
  expect(is(Number, new Number(0))).toBeTrue()
  expect(is(Object, {})).toBeTrue()
  expect(is(RegExp, /(?:)/)).toBeTrue()
  expect(is(String, new String(''))).toBeTrue()
})

test('works with user-defined types', () => {
  function Foo(){}
  function Bar(){}
  Bar.prototype = new Foo()

  const foo = new Foo()
  const bar = new Bar()

  expect(is(Foo, foo)).toBeTrue()
  expect(is(Bar, bar)).toBeTrue()
  expect(is(Foo, bar)).toBeTrue()
  expect(is(Bar, foo)).toBeFalse()
})

test('does not coerce', () => {
  expect(is(Boolean, 1)).toBeFalse()
  expect(is(Number, '1')).toBeFalse()
  expect(is(Number, false)).toBeFalse()
})

test('recognizes primitives as their object equivalents', () => {
  expect(is(Boolean, false)).toBeTrue()
  expect(is(Number, 0)).toBeTrue()
  expect(is(String, '')).toBeTrue()
})

test('does not consider primitives to be instances of Object', () => {
  expect(is(Object, false)).toBeFalse()
  expect(is(Object, 0)).toBeFalse()
  expect(is(Object, '')).toBeFalse()
})

---------------

isEmpty

isEmpty<T>(x: T): boolean

It returns true if x is empty.

const result = [
  R.isEmpty(''),
  R.isEmpty({ x : 0 })
]
// => [true, false]

Try this R.isEmpty example in Rambda REPL

All TypeScript definitions
isEmpty<T>(x: T): boolean;
R.isEmpty source
import { type } from './type.js'

export function isEmpty(input){
  const inputType = type(input)
  if ([ 'Undefined', 'NaN', 'Number', 'Null' ].includes(inputType))
    return false
  if (!input) return true

  if (inputType === 'Object'){
    return Object.keys(input).length === 0
  }

  if (inputType === 'Array'){
    return input.length === 0
  }

  return false
}
Tests
import { isEmpty } from './isEmpty.js'

test('happy', () => {
  expect(isEmpty(undefined)).toBeFalse()
  expect(isEmpty('')).toBeTrue()
  expect(isEmpty(null)).toBeFalse()
  expect(isEmpty(' ')).toBeFalse()
  expect(isEmpty(new RegExp(''))).toBeFalse()
  expect(isEmpty([])).toBeTrue()
  expect(isEmpty([ [] ])).toBeFalse()
  expect(isEmpty({})).toBeTrue()
  expect(isEmpty({ x : 0 })).toBeFalse()
  expect(isEmpty(0)).toBeFalse()
  expect(isEmpty(NaN)).toBeFalse()
  expect(isEmpty([ '' ])).toBeFalse()
})

---------------

isNil

isNil(x: any): x is null | undefined

It returns true if x is either null or undefined.

const result = [
  R.isNil(null),
  R.isNil(1),
]
// => [true, false]

Try this R.isNil example in Rambda REPL

All TypeScript definitions
isNil(x: any): x is null | undefined;
R.isNil source
export function isNil(x){
  return x === undefined || x === null
}
Tests
import { isNil } from './isNil.js'

test('happy', () => {
  expect(isNil(null)).toBeTrue()

  expect(isNil(undefined)).toBeTrue()

  expect(isNil([])).toBeFalse()
})

---------------

isNotEmpty

isNotEmpty<T>(value: T[]): value is NonEmptyArray<T>
All TypeScript definitions
isNotEmpty<T>(value: T[]): value is NonEmptyArray<T>;
isNotEmpty<T>(value: readonly T[]): value is ReadonlyNonEmptyArray<T>;
isNotEmpty(value: any): boolean;

---------------

isNotNil

isNotNil<T>(value: T): value is NonNullable<T>
const result = [
  R.isNotNil(null),
  R.isNotNil(undefined),
  R.isNotNil([]),
]
// => [false, false, true]

Try this R.isNotNil example in Rambda REPL

All TypeScript definitions
isNotNil<T>(value: T): value is NonNullable<T>;
R.isNotNil source
export function isNotNil(input) {
  return input != null
}
Tests
import { isNotNil } from './isNotNil'

test('tests a value for `null` or `undefined`', () => {
  expect(isNotNil(void 0)).toBe(false)
  expect(isNotNil(undefined)).toBe(false)
  expect(isNotNil(null)).toBe(false)
  expect(isNotNil([])).toBe(true)
  expect(isNotNil({})).toBe(true)
  expect(isNotNil(0)).toBe(true)
  expect(isNotNil('')).toBe(true)
})

---------------

isPromise

isPromise(input: any): boolean
All TypeScript definitions
isPromise(input: any): boolean;

---------------

isType

isType(targetType: RambdaTypes, input: any): boolean

It returns true if targetType is equal to type of input according to R.type.

R.isType('Async',R.delay(1000))
// => true

Try this R.isType example in Rambda REPL

All TypeScript definitions
isType(targetType: RambdaTypes, input: any): boolean;
isType(targetType: RambdaTypes): (input: any) => boolean;
R.isType source
import { type } from './type.js'

export function isType(xType, x){
  if (arguments.length === 1){
    return xHolder => isType(xType, xHolder)
  }

  return type(x) === xType
}
Tests
import { delay } from './delay.js'
import { isType } from './isType.js'

const list = [ 1, 2, 3 ]

test('array', () => {
  expect(isType('Array', list)).toBeTruthy()
  expect(isType('Array')([])).toBeTruthy()
})

test('promise', () => {
  expect(isType('Promise', Promise.resolve(1))).toBeTruthy()
})

test('async', () => {
  async function fn(){}

  expect(isType('Promise', fn)).toBeTruthy()
})

test('with R.delay', () => {
  expect(isType('Function', delay)).toBeTruthy()
  expect(isType('Promise', delay(100))).toBeTruthy()
})

---------------

isValid

isValid({input: object, schema: Schema}: IsValid): boolean

It checks if input is following schema specifications.

If validation fails, it returns false.

Please check the detailed explanation as it is hard to write a short description for this method.

💥 Independently, somebody else came with very similar idea called superstruct

const input = {a: ['foo', 'bar']}
const invalidInput = {a: ['foo', 'bar', 1]}
const schema = {a: [String]}
const result = [
  R.isValid({schema, input}),
  R.isValid({schema, input: invalidInput})
]
// => [true, false]

Try this R.isValid example in Rambda REPL

All TypeScript definitions
isValid({input: object, schema: Schema}: IsValid): boolean;
R.isValid source
import { isArray } from './_internals/isArray.js'
import { all } from './all.js'
import { any } from './any.js'
import { includes } from './includes.js'
import { init } from './init.js'
import { test } from './test.js'
import { toLower } from './toLower.js'
import { type } from './type.js'

export function isPrototype(input){
  const currentPrototype = input.prototype
  const list = [ Number, String, Boolean, Promise ]
  let toReturn = false
  let counter = -1
  while (++counter < list.length && !toReturn){
    if (currentPrototype === list[ counter ].prototype) toReturn = true
  }

  return toReturn
}

export function prototypeToString(input){
  const currentPrototype = input.prototype
  const list = [ Number, String, Boolean, Promise ]
  const translatedList = [ 'Number', 'String', 'Boolean', 'Promise' ]
  let found
  let counter = -1

  while (++counter < list.length){
    if (currentPrototype === list[ counter ].prototype) found = counter
  }

  return translatedList[ found ]
}

const typesWithoutPrototype = [ 'any', 'promise', 'async', 'function' ]

export function fromPrototypeToString(rule){
  if (
    isArray(rule) ||
    rule === undefined ||
    rule === null ||
    rule.prototype === undefined ||
    typesWithoutPrototype.includes(rule)
  ){
    return {
      rule,
      parsed : false,
    }
  }
  if (String.prototype === rule.prototype){
    return {
      rule   : 'string',
      parsed : true,
    }
  }
  if (Boolean.prototype === rule.prototype){
    return {
      rule   : 'boolean',
      parsed : true,
    }
  }
  if (Number.prototype === rule.prototype){
    return {
      rule   : 'number',
      parsed : true,
    }
  }

  return {
    rule   : type(rule.prototype).toLowerCase(),
    parsed : true,
  }
}

function getRuleAndType(schema, requirementRaw){
  const ruleRaw = schema[ requirementRaw ]
  const typeIs = type(ruleRaw)
  const { rule, parsed } = fromPrototypeToString(ruleRaw)

  return {
    rule,
    ruleType : parsed ? 'String' : typeIs,
  }
}

export function isValid({ input, schema }){
  if (input === undefined || schema === undefined) return false

  let flag = true
  const boom = boomFlag => {
    if (!boomFlag){
      flag = false
    }
  }

  for (const requirementRaw in schema){
    if (flag){
      const isOptional = requirementRaw.endsWith('?')
      const requirement = isOptional ? init(requirementRaw) : requirementRaw

      const { rule, ruleType } = getRuleAndType(schema, requirementRaw)
      const inputProp = input[ requirement ]
      const inputPropType = type(input[ requirement ])

      const ok = isOptional && inputProp !== undefined || !isOptional

      if (!ok || rule === 'any' && inputProp != null || rule === inputProp)
        continue

      if (ruleType === 'Object'){
        /**
         * This rule is standalone schema, so we recursevly call `isValid`
         */
        const isValidResult = isValid({
          input  : inputProp,
          schema : rule,
        })
        boom(isValidResult)
      } else if (ruleType === 'String'){
        /**
         * Rule is actual rule such as 'number', so the two types are compared
         */
        boom(toLower(inputPropType) === rule)
      } else if (typeof rule === 'function'){
        /**
         * Rule is function so we pass to it the input
         */
        boom(rule(inputProp))
      } else if (ruleType === 'Array' && inputPropType === 'String'){
        /**
         * Enum case | rule is like a: ['foo', 'bar']
         */
        boom(includes(inputProp, rule))
      } else if (
        ruleType === 'Array' &&
        rule.length === 1 &&
        inputPropType === 'Array'
      ){
        /**
         * 1. array of type | rule is like a: ['number']
         * 2. rule is like a: [{foo: 'string', bar: 'number'}]
         */
        const [ currentRule ] = rule
        const currentRuleType = type(currentRule)

        //Check if rule is invalid
        boom(currentRuleType === 'String' ||
            currentRuleType === 'Object' ||
            isPrototype(currentRule))

        if (currentRuleType === 'Object' && flag){
          /**
           * 2. rule is like a: [{from: 'string'}]
           */
          const isValidResult = all(inputPropInstance =>
            isValid({
              input  : inputPropInstance,
              schema : currentRule,
            }),
          inputProp)
          boom(isValidResult)
        } else if (flag){
          /**
           * 1. array of type
           */

          const actualRule =
            currentRuleType === 'String' ?
              currentRule :
              prototypeToString(currentRule)
          const isInvalidResult = any(inputPropInstance =>
            type(inputPropInstance).toLowerCase() !==
              actualRule.toLowerCase(),
          inputProp)
          boom(!isInvalidResult)
        }
      } else if (ruleType === 'RegExp' && inputPropType === 'String'){
        boom(test(rule, inputProp))
      } else {
        boom(false)
      }
    }
  }

  return flag
}
Tests
import { delay } from './delay.js'
import { isPrototype, isValid } from './isValid.js'

test('is prototype', () => {
  expect(isPrototype(Promise)).toBeTrue()
  expect(isPrototype(Number)).toBeTrue()
  expect(isPrototype(Boolean)).toBeTrue()
  expect(isPrototype(String)).toBeTrue()
  expect(isPrototype(0)).toBeFalse()
})

test('prototype inside array', () => {
  const input = { a : [ 1, 2, 3, 4 ] }
  const schema = { a : [ Number ] }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('with Promise prototype', () => {
  const input = { a : [ delay(1), delay(2) ] }
  const schema = { a : [ Promise ] }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('object prototype as rule - true', () => {
  const input = { a : {} }
  const schema = { a : Object }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('list of functions', () => {
  const input = { a : [ () => {}, delay ] }
  const schema = { a : [ 'function' ] }

  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('function schema type can be only string', () => {
  const input = { a : [ () => {}, delay ] }
  const schema = { a : [ Function ] }

  expect(isValid({
    input,
    schema,
  })).toBeFalsy()
})

test('object prototype as rule - false', () => {
  const input = { a : null }
  const schema = { a : Object }
  expect(isValid({
    input,
    schema,
  })).toBeFalsy()
})

test('number prototype as rule - true', () => {
  const input = { a : 1 }
  const schema = { a : Number }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('array prototype as rule - true', () => {
  const input = { a : [ 1, 2, 3 ] }
  const schema = { a : Array }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('array prototype as rule - false', () => {
  const input = { a : null }
  const schema = { a : Array }
  expect(isValid({
    input,
    schema,
  })).toBeFalsy()
})

test('string prototype as rule - true', () => {
  const input = { a : 'foo' }
  const schema = { a : String }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('string prototype as rule - false', () => {
  const input = { a : null }
  const schema = { a : String }
  expect(isValid({
    input,
    schema,
  })).toBeFalsy()
})

test('boolean prototype as rule - true', () => {
  const input = { a : true }
  const schema = { a : Boolean }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('boolean prototype as rule - false', () => {
  const input = { a : null }
  const schema = { a : Boolean }
  expect(isValid({
    input,
    schema,
  })).toBeFalsy()
})

test('regex prototype cannot be rule - true', () => {
  const input = { a : /foo/g }
  const schema = { a : new RegExp('foo') }
  expect(isValid({
    input,
    schema,
  })).toBeFalsy()
})

test('undefined as a rule - true', () => {
  const input = { a : undefined }
  const schema = { a : undefined }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('undefined as a rule - false', () => {
  const input = { a : null }
  const schema = { a : undefined }
  expect(isValid({
    input,
    schema,
  })).toBeFalsy()
})

test('null as a rule - true', () => {
  const input = { a : null }
  const schema = { a : null }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('null as a rule - false', () => {
  const input = { a : undefined }
  const schema = { a : null }
  expect(isValid({
    input,
    schema,
  })).toBeFalsy()
})

test('`any` safeguard against `null`', () => {
  const input = { a : null }
  const schema = { a : 'any' }
  expect(isValid({
    input,
    schema,
  })).toBeFalsy()
})

test('`any` safeguard against `undefined`', () => {
  const input = { a : undefined }
  const schema = { a : 'any' }
  expect(isValid({
    input,
    schema,
  })).toBeFalsy()
})

test('type can be `"any"`', () => {
  const input = { a : () => {} }
  const schema = { a : 'any' }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('type can be `"function"`', () => {
  const input = { a : () => {} }
  const schema = { a : 'function' }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('type can be `promise`', () => {
  const input = {
    a : delay(1999),
    b : async () => {},
  }
  const schema = {
    a : 'promise',
    b : 'promise',
  }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('type can be `promise` list', () => {
  const input = { a : [ delay(1999) ] }
  const schema = { a : [ 'promise' ] }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('function as schema - false', () => {
  const input = {
    a : {
      ab : () => true,
      ac : 3,
    },
    c : [ 1, 2 ],
  }
  const schema = {
    'a' : {
      ab : /fo/,
      ac : 'number',
    },
    'b?' : 'string',
    'c'  : [ 'number' ],
  }
  expect(isValid({
    input,
    schema,
  })).toBeFalsy()
})

test('regex ok', () => {
  const input = {
    a : {
      ab : 'foo',
      ac : 3,
    },
    c : [ 1, 2 ],
  }
  const schema = {
    'a' : {
      ab : /fo/,
      ac : 'number',
    },
    'b?' : 'string',
    'c'  : [ 'number' ],
  }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('regex !ok', () => {
  const input = {
    a : {
      ab : 'foo',
      ac : 3,
    },
    c : [ 1, 2 ],
  }
  const schema = {
    'a' : {
      ab : /ba/,
      ac : 'number',
    },
    'b?' : 'string',
    'c'  : [ 'number' ],
  }
  expect(isValid({
    input,
    schema,
  })).toBeFalsy()
})

test('optional props is missing', () => {
  const input = {
    a : {
      ab : 'foo',
      ac : 3,
    },
    c : [ 1, 2 ],
  }
  const schema = {
    'a' : {
      ab : 'string',
      ac : 'number',
    },
    'b?' : 'string',
    'c'  : [ 'number' ],
  }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('optional props is wrong type', () => {
  const input = {
    a : {
      ab : 'foo',
      ac : 3,
    },
    b : [],
    c : [ 1, 2 ],
  }
  const schema = {
    'a' : {
      ab : 'string',
      ac : 'number',
    },
    'b?' : 'string',
    'c'  : [ 'number' ],
  }
  expect(isValid({
    input,
    schema,
  })).toBeFalsy()
})

test('optional props - nested', () => {
  const input = {
    a : {
      ab : 'foo',
      ac : 3,
    },
    b : [],
    c : [ 1, 2 ],
  }
  const schema = {
    a : {
      'ab'  : 'string',
      'ac?' : 'number',
    },
    b : 'array',
    c : [ 'number' ],
  }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('optional props is missing - nested', () => {
  const input = {
    a : { ab : 'foo' },
    b : [],
    c : [ 1, 2 ],
  }
  const schema = {
    a : {
      'ab'  : 'string',
      'ac?' : 'number',
    },
    b : 'array',
    c : [ 'number' ],
  }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('optional props is wrong type - nested', () => {
  const input = {
    a : {
      ab : 'foo',
      ac : 'bar',
    },
    b : [],
    c : [ 1, 2 ],
  }
  const schema = {
    a : {
      'ab'  : 'string',
      'ac?' : 'number',
    },
    b : 'array',
    c : [ 'number' ],
  }
  expect(isValid({
    input,
    schema,
  })).toBeFalsy()
})

test('nested schema', () => {
  const input = {
    a : {
      b : 'str',
      c : 3,
      d : 'str',
    },
    b : 'foo',
  }
  const schema = {
    a : {
      b : 'string',
      c : 'number',
      d : 'string',
    },
    b : 'string',
  }

  expect(isValid({
    input,
    schema,
  })).toBeTruthy()

  const invalidInputFirst = {
    a : {
      b : 'str',
      c : 3,
      d : 'str',
    },
    b : 5,
  }

  expect(isValid({
    input : invalidInputFirst,
    schema,
  })).toBeFalsy()

  const invalidInputSecond = {
    a : {
      b : 'str',
      c : 'str',
      d : 'str',
    },
    b : 5,
  }

  expect(isValid({
    input : invalidInputSecond,
    schema,
  })).toBeFalsy()

  const invalidInputThird = {
    a : { b : 'str' },
    b : 5,
  }

  expect(isValid({
    input : invalidInputThird,
    schema,
  })).toBeFalsy()
})

test('array of type', () => {
  const input = {
    a : [ 1, 2 ],
    b : 'foo',
  }
  const schema = {
    a : [ 'number' ],
    b : 'string',
  }

  expect(isValid({
    input,
    schema,
  })).toBeTruthy()

  const invalidInput = {
    a : [ 1, '1' ],
    b : 'foo',
  }

  expect(isValid({
    input : invalidInput,
    schema,
  })).toBeFalsy()
})

test('function as rule', () => {
  const input = {
    a : [ 1, 2, 3, 4 ],
    b : 'foo',
  }
  const invalidInput = {
    a : [ 4 ],
    b : 'foo',
  }

  const schema = {
    a : x => x.length > 2,
    b : 'string',
  }

  expect(isValid({
    input,
    schema,
  })).toBeTruthy()

  expect(isValid({
    input : invalidInput,
    schema,
  })).toBeFalsy()
})

test('input prop is undefined', () => {
  const input = { b : 3 }
  const schema = { a : 'number' }

  expect(isValid({
    input,
    schema,
  })).toBeFalsy()
})

test('enum', () => {
  const input = { a : 'foo' }
  const invalidInput = { a : '' }

  const schema = { a : [ 'foo', 'bar', 'baz' ] }

  expect(isValid({
    input,
    schema,
  })).toBeTruthy()

  expect(isValid({
    input : invalidInput,
    schema,
  })).toBeFalsy()
})

test('readme example', () => {
  const basicSchema = { a : [ 'string' ] }
  const schema = {
    b : [ basicSchema ],
    c : {
      d : { e : 'boolean' },
      f : 'array',
    },
    g : [ 'foo', 'bar', 'baz' ],
  }
  const input = {
    b : [ { a : [ 'led', 'zeppelin' ] } ],
    c : {
      d : { e : true },
      f : [ 'any', 1, null, 'value' ],
    },
    g : 'foo',
  }

  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('should allow additional properties', () => {
  const input = {
    title : 'You shook me',
    year  : 1969,
  }

  expect(isValid({
    input,
    schema : { title : 'string' },
  })).toBeTruthy()
})

test('accepts values as schemas', () => {
  const input = {
    title : 'You shook me',
    genre : 'Blues',
    year  : 1969,
  }
  const schema = {
    title : 'You shook me',
    year  : 1969,
  }
  expect(isValid({
    input,
    schema,
  })).toBeTruthy()
})

test('compatible schemas with nested object', () => {
  const input = {
    foo : 'bar',
    baz : { a : { b : 'c' } },
  }
  const invalidInputFirst = {
    foo : 'bar',
    baz : { a : { b : 1 } },
  }
  const invalidInputSecond = {
    foo : 'bar',
    baz : { a : { b : [] } },
  }
  const invalidInputThird = {
    foo : 'bar',
    baz : { a : { b : null } },
  }
  const schema = {
    foo : 'string',
    baz : { a : { b : 'string' } },
  }

  expect(isValid({
    input,
    schema,
  })).toBeTruthy()

  expect(isValid({
    input : invalidInputFirst,
    schema,
  })).toBeFalsy()
  expect(isValid({
    input : invalidInputSecond,
    schema,
  })).toBeFalsy()
  expect(isValid({
    input : invalidInputThird,
    schema,
  })).toBeFalsy()
})

test('should return true when schema is empty object', () => {
  expect(isValid({
    input  : { a : 1 },
    schema : {},
  })).toBeTruthy()
})

test('when schema is undefined', () => {
  expect(isValid({
    input  : { a : 1 },
    schema : undefined,
  })).toBeFalsy()
})

test('should return false with invalid schema rule', () => {
  const input = {
    foo : 'bar',
    a   : {},
  }
  const inputSecond = { foo : 'bar' }

  const schema = {
    foo : 'string',
    baz : { a : {} },
  }

  expect(isValid({
    input,
    schema,
  })).toBeFalsy()

  expect(isValid({
    input : inputSecond,
    schema,
  })).toBeFalsy()
})

test('array of schemas', () => {
  const input = {
    b : [
      {
        a : 'led',
        b : 1,
      },
      {
        a : 'dancing',
        b : 1,
      },
    ],
  }
  const basicSchema = {
    a : String,
    b : Number,
  }
  const schema = { b : [ basicSchema ] }
  const result = isValid({
    input,
    schema,
  })

  expect(result).toBeTruthy()
})

---------------

isValidAsync

isValidAsync(x: IsValidAsync): Promise<boolean>

Asynchronous version of R.isValid

const input = {a: 1, b: 2}
const invalidInput = {a: 1, b: 'foo'}
const schema = {a: Number, b: async x => {
  await R.delay(100)
  return typeof x === 'number'
}}

const result = await Promise.all([
  R.isValidAsync({schema, input}),
  R.isValidAsync({schema, input: invalidInput})
])
// => [true, false]

Try this R.isValidAsync example in Rambda REPL

All TypeScript definitions
isValidAsync(x: IsValidAsync): Promise<boolean>;
R.isValidAsync source
import { forEach } from './forEach.js'
import { isPromise } from './isPromise.js'
import { isValid } from './isValid.js'

export async function isValidAsync({ schema, input }){
  const asyncSchema = {}
  const simpleSchema = {}
  forEach((rule, prop) => {
    if (isPromise(rule)){
      asyncSchema[ prop ] = rule
    } else {
      simpleSchema[ prop ] = rule
    }
  }, schema)

  if (Object.keys(asyncSchema).length === 0)
    return isValid({
      input,
      schema,
    })

  if (
    !isValid({
      input,
      schema : simpleSchema,
    })
  )
    return false

  let toReturn = true

  for (const singleRuleProp in asyncSchema){
    if (toReturn){
      const validated = await asyncSchema[ singleRuleProp ](input[ singleRuleProp ])
      if (!validated) toReturn = false
    }
  }

  return toReturn
}
Tests
import { result } from 'lodash'

import { delay } from './delay.js'
import { isValidAsync } from './isValidAsync.js'

const simplePredicate = async x => {
  await delay(100)

  return x > 5
}

test('happy', async () => {
  const input = {
    a          : 1,
    b          : 7,
    c          : 9,
    additional : 'foo',
  }
  const invalidInput = {
    a : 1,
    b : 2,
    c : 9,
  }
  const schema = {
    a : Number,
    b : simplePredicate,
    c : simplePredicate,
  }
  const invalidSchema = {
    a : Boolean,
    b : simplePredicate,
    c : simplePredicate,
  }
  const result = await isValidAsync({
    input,
    schema,
  })
  const invalidResult = await isValidAsync({
    input,
    schema : invalidSchema,
  })
  const withInvalidInput = await isValidAsync({
    input : invalidInput,
    schema,
  })
  expect(result).toBeTruthy()
  expect(invalidResult).toBeFalsy()
  expect(withInvalidInput).toBeFalsy()
})

test('without async rules', async () => {
  const input = {
    a : 1,
    b : 7,
  }
  const schema = {
    a : Number,
    b : x => x > 2,
  }
  const invalidSchema = {
    a : Number,
    b : Boolean,
  }
  const result = await isValidAsync({
    input,
    schema,
  })
  const invalidResult = await isValidAsync({
    input,
    schema : invalidSchema,
  })

  expect(result).toBeTruthy()
  expect(invalidResult).toBeFalsy()
})

test('readme example', async () => {
  const input = {
    a : 1,
    b : 2,
  }
  const invalidInput = {
    a : 1,
    b : 'foo',
  }
  const schema = {
    a : Number,
    b : async x => {
      await delay(100)

      return typeof x === 'number'
    },
  }
  const result = await Promise.all([
    isValidAsync({
      schema,
      input,
    }),
    isValidAsync({
      schema,
      input : invalidInput,
    }),
  ])
  expect(result).toEqual([ true, false ])
})

---------------

join

join<T>(glue: string, list: T[]): string

It returns a string of all list instances joined with a glue.

R.join('-', [1, 2, 3])  // => '1-2-3'

Try this R.join example in Rambda REPL

All TypeScript definitions
join<T>(glue: string, list: T[]): string;
join<T>(glue: string): (list: T[]) => string;
R.join source
export function join(glue, list){
  if (arguments.length === 1) return _list => join(glue, _list)

  return list.join(glue)
}
Tests
import { join } from './join.js'

test('curry', () => {
  expect(join('|')([ 'foo', 'bar', 'baz' ])).toBe('foo|bar|baz')

  expect(join('|', [ 1, 2, 3 ])).toBe('1|2|3')

  const spacer = join(' ')

  expect(spacer([ 'a', 2, 3.4 ])).toBe('a 2 3.4')
})

---------------

juxt

juxt<A extends any[], R1>(fns: [(...a: A) => R1]): (...a: A) => [R1]

It applies list of function to a list of inputs.

const getRange = juxt([ Math.min, Math.max, Math.min ])
const result = getRange(
  3, 4, 9, -3
)
// => [-3, 9, -3]

Try this R.juxt example in Rambda REPL

All TypeScript definitions
juxt<A extends any[], R1>(fns: [(...a: A) => R1]): (...a: A) => [R1];
juxt<A extends any[], R1, R2>(fns: [(...a: A) => R1, (...a: A) => R2]): (...a: A) => [R1, R2];
juxt<A extends any[], R1, R2, R3>(fns: [(...a: A) => R1, (...a: A) => R2, (...a: A) => R3]): (...a: A) => [R1, R2, R3];
juxt<A extends any[], R1, R2, R3, R4>(fns: [(...a: A) => R1, (...a: A) => R2, (...a: A) => R3, (...a: A) => R4]): (...a: A) => [R1, R2, R3, R4];
juxt<A extends any[], R1, R2, R3, R4, R5>(fns: [(...a: A) => R1, (...a: A) => R2, (...a: A) => R3, (...a: A) => R4, (...a: A) => R5]): (...a: A) => [R1, R2, R3, R4, R5];
juxt<A extends any[], U>(fns: Array<(...args: A) => U>): (...args: A) => U[];
R.juxt source
export function juxt(listOfFunctions){
  return (...args) => listOfFunctions.map(fn => fn(...args))
}
Tests
import { juxt } from './juxt.js'

test('happy', () => {
  const fn = juxt([ Math.min, Math.max, Math.min ])
  const result = fn(
    3, 4, 9, -3
  )
  expect(result).toEqual([ -3, 9, -3 ])
})

---------------

keys

keys<T extends object>(x: T): (keyof T & string)[]

It applies Object.keys over x and returns its keys.

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

Try this R.keys example in Rambda REPL

All TypeScript definitions
keys<T extends object>(x: T): (keyof T & string)[];
keys<T>(x: T): string[];
R.keys source
export function keys(x){
  return Object.keys(x)
}
Tests
import { keys } from './keys.js'

test('happy', () => {
  expect(keys({ a : 1 })).toEqual([ 'a' ])
})

---------------

last

last(str: ''): undefined

It returns the last element of input, as the input can be either a string or an array. It returns undefined if array has length of 0.

const result = [
  R.last([1, 2, 3]),
  R.last('foo'),
]
// => [3, 'o']

Try this R.last example in Rambda REPL

All TypeScript definitions
last(str: ''): undefined;
last(str: string): string;
last(list: readonly[]): undefined;
last(list: never[]): undefined;
last<T extends unknown[]>(array: T): LastArrayElement<T>;
last<T extends readonly unknown[]>(array: T): LastArrayElement<T>;
last(str: string): string | undefined;
R.last source
export function last(listOrString){
  if (typeof listOrString === 'string'){
    return listOrString[ listOrString.length - 1 ] || ''
  }

  return listOrString[ listOrString.length - 1 ]
}
Tests
import { last } from './last.js'

test('with list', () => {
  expect(last([ 1, 2, 3 ])).toBe(3)
  expect(last([])).toBeUndefined()
})

test('with string', () => {
  expect(last('abc')).toBe('c')
  expect(last('')).toBe('')
})

---------------

lastIndexOf

lastIndexOf<T>(target: T, list: T[]): number

It returns the last index of target in list array.

R.equals is used to determine equality between target and members of list.

If there is no such index, then -1 is returned.

const list = [1, 2, 3, 1, 2, 3]
const result = [
  R.lastIndexOf(2, list),
  R.lastIndexOf(4, list),
]
// => [4, -1]

Try this R.lastIndexOf example in Rambda REPL

All TypeScript definitions
lastIndexOf<T>(target: T, list: T[]): number;
lastIndexOf<T>(target: T): (list: T[]) => number;
R.lastIndexOf source
import { _lastIndexOf } from './equals.js'

export function lastIndexOf(valueToFind, list){
  if (arguments.length === 1){
    return _list => _lastIndexOf(valueToFind, _list)
  }

  return _lastIndexOf(valueToFind, list)
}
Tests
import { lastIndexOf as lastIndexOfRamda } from 'ramda'

import { compareCombinations } from './_internals/testUtils.js'
import { possibleIterables, possibleTargets } from './indexOf.spec.js'
import { lastIndexOf } from './lastIndexOf.js'

test('with NaN', () => {
  expect(lastIndexOf(NaN, [ NaN ])).toBe(0)
})

test('will throw with bad input', () => {
  expect(lastIndexOfRamda([], true)).toBe(-1)
  expect(() => indexOf([], true)).toThrowErrorMatchingInlineSnapshot('"indexOf is not defined"')
})

test('without list of objects - no R.equals', () => {
  expect(lastIndexOf(3, [ 1, 2, 3, 4 ])).toBe(2)
  expect(lastIndexOf(10)([ 1, 2, 3, 4 ])).toBe(-1)
})

test('list of objects uses R.equals', () => {
  const listOfObjects = [ { a : 1 }, { b : 2 }, { c : 3 } ]
  expect(lastIndexOf({ c : 4 }, listOfObjects)).toBe(-1)
  expect(lastIndexOf({ c : 3 }, listOfObjects)).toBe(2)
})

test('list of arrays uses R.equals', () => {
  const listOfLists = [ [ 1 ], [ 2, 3 ], [ 2, 3, 4 ], [ 2, 3 ], [ 1 ], [] ]
  expect(lastIndexOf([], listOfLists)).toBe(5)
  expect(lastIndexOf([ 1 ], listOfLists)).toBe(4)
  expect(lastIndexOf([ 2, 3, 4 ], listOfLists)).toBe(2)
  expect(lastIndexOf([ 2, 3, 5 ], listOfLists)).toBe(-1)
})

test('with string as iterable', () => {
  expect(() => lastIndexOf('a', 'abc')).toThrowErrorMatchingInlineSnapshot('"Cannot read property \'indexOf\' of abc"')
  expect(lastIndexOfRamda('a', 'abc')).toBe(0)
})

describe('brute force', () => {
  compareCombinations({
    fn          : lastIndexOf,
    fnRamda     : lastIndexOfRamda,
    firstInput  : possibleTargets,
    secondInput : possibleIterables,
    callback    : errorsCounters => {
      expect(errorsCounters).toMatchInlineSnapshot(`
        {
          "ERRORS_MESSAGE_MISMATCH": 0,
          "ERRORS_TYPE_MISMATCH": 34,
          "RESULTS_MISMATCH": 0,
          "SHOULD_NOT_THROW": 51,
          "SHOULD_THROW": 0,
          "TOTAL_TESTS": 170,
        }
      `)
    },
  })
})

---------------

length

length<T>(input: T[]): number

It returns the length property of list or string input.

const result = [
  R.length([1, 2, 3, 4]),
  R.length('foo'),
]
// => [4, 3]

Try this R.length example in Rambda REPL

All TypeScript definitions
length<T>(input: T[]): number;
R.length source
import { isArray } from './_internals/isArray.js'

export function length(x){
  if (isArray(x)) return x.length
  if (typeof x === 'string') return x.length

  return NaN
}
Tests
import { length as lengthRamda } from 'ramda'

import { length } from './length.js'

test('happy', () => {
  expect(length('foo')).toBe(3)
  expect(length([ 1, 2, 3 ])).toBe(3)
  expect(length([])).toBe(0)
})

test('with empty string', () => {
  expect(length('')).toBe(0)
})

test('with bad input returns NaN', () => {
  expect(length(0)).toBeNaN()
  expect(length({})).toBeNaN()
  expect(length(null)).toBeNaN()
  expect(length(undefined)).toBeNaN()
})

test('with length as property', () => {
  const input1 = { length : '123' }
  const input2 = { length : null }
  const input3 = { length : '' }

  expect(length(input1)).toBeNaN()
  expect(lengthRamda(input1)).toBeNaN()
  expect(length(input2)).toBeNaN()
  expect(lengthRamda(input2)).toBeNaN()
  expect(length(input3)).toBeNaN()
  expect(lengthRamda(input3)).toBeNaN()
})

---------------

lens

lens<S, A>(getter: (s: S) => A, setter: (a: A, s: S) => S): Lens<S, A>

It returns a lens for the given getter and setter functions.

The getter gets the value of the focus; the setter sets the value of the focus.

The setter should not mutate the data structure.

const xLens = R.lens(R.prop('x'), R.assoc('x'));

R.view(xLens, {x: 1, y: 2}) // => 1
R.set(xLens, 4, {x: 1, y: 2}) // => {x: 4, y: 2}
R.over(xLens, R.negate, {x: 1, y: 2}) // => {x: -1, y: 2}

Try this R.lens example in Rambda REPL

All TypeScript definitions
lens<S, A>(getter: (s: S) => A, setter: (a: A, s: S) => S): Lens<S, A>;
R.lens source
export function lens(getter, setter){
  return function (functor){
    return function (target){
      return functor(getter(target)).map(focus => setter(focus, target))
    }
  }
}

---------------

lensEq

lensEq(lens: Function, value: any, data: any): boolean

It returns true if data structure focused by the given lens equals to the target value.

R.equals is used to determine equality.

💥 Idea for this method comes from ramda-adjunct library

const list = [ 1, 2, 3 ]
const lens = R.lensIndex(0)
const result = R.lensEq(
  lens, 1, list
)
// => true

Try this R.lensEq example in Rambda REPL

All TypeScript definitions
lensEq(lens: Function, value: any, data: any): boolean;
lensEq(lens: Function, value: any): (data: any) => boolean;
lensEq(lens: Function): (value: any) => (data: any) => boolean;
R.lensEq source
import { curry } from './curry.js'
import { equals } from './equals.js'
import { view } from './view.js'

function lensEqFn(
  lens, target, input
){
  return equals(view(lens, input), target)
}

export const lensEq = curry(lensEqFn)
Tests
import { lensEq } from './lensEq.js'
import { lensIndex } from './lensIndex.js'
import { lensPath } from './lensPath.js'

test('with list', () => {
  const list = [ 1, 2, 3 ]
  const lens = lensIndex(0)
  expect(lensEq(
    lens, 1, list
  )).toBeTrue()
  expect(lensEq(lens, 2)(list)).toBeFalse()
})

test('with R.lensPath', () => {
  const input = { a : { b : { c : 1 } } }
  const target = { c : 1 }
  const lens = lensPath('a.b')

  expect(lensEq(lens)(target)(input)).toBeTrue()
  expect(lensEq(
    lens, target, { c : 2 }
  )).toBeFalse()
})

---------------

lensIndex

lensIndex<A>(n: number): Lens<A[], A>

It returns a lens that focuses on specified index.

const list = ['a', 'b', 'c']
const headLens = R.lensIndex(0)

R.view(headLens, list) // => 'a'
R.set(headLens, 'x', list) // => ['x', 'b', 'c']
R.over(headLens, R.toUpper, list) // => ['A', 'b', 'c']

Try this R.lensIndex example in Rambda REPL

All TypeScript definitions
lensIndex<A>(n: number): Lens<A[], A>;
lensIndex<A extends any[], N extends number>(n: N): Lens<A, A[N]>;
R.lensIndex source
import { lens } from './lens.js'
import { nth } from './nth.js'
import { update } from './update.js'

export function lensIndex(index){
  return lens(nth(index), update(index))
}
Tests
import { compose } from './compose.js'
import { keys } from './keys.js'
import { lensIndex } from './lensIndex.js'
import { over } from './over.js'
import { set } from './set.js'
import { view } from './view.js'

const testList = [ { a : 1 }, { b : 2 }, { c : 3 } ]

test('focuses list element at the specified index', () => {
  expect(view(lensIndex(0), testList)).toEqual({ a : 1 })
})

test('returns undefined if the specified index does not exist', () => {
  expect(view(lensIndex(10), testList)).toBeUndefined()
})

test('sets the list value at the specified index', () => {
  expect(set(
    lensIndex(0), 0, testList
  )).toEqual([ 0, { b : 2 }, { c : 3 } ])
})

test('applies function to the value at the specified list index', () => {
  expect(over(
    lensIndex(2), keys, testList
  )).toEqual([ { a : 1 }, { b : 2 }, [ 'c' ] ])
})

test('can be composed', () => {
  const nestedList = [ 0, [ 10, 11, 12 ], 1, 2 ]
  const composedLens = compose(lensIndex(1), lensIndex(0))

  expect(view(composedLens, nestedList)).toBe(10)
})

test('set s (get s) === s', () => {
  expect(set(
    lensIndex(0), view(lensIndex(0), testList), testList
  )).toEqual(testList)
})

test('get (set s v) === v', () => {
  expect(view(lensIndex(0), set(
    lensIndex(0), 0, testList
  ))).toBe(0)
})

test('get (set(set s v1) v2) === v2', () => {
  expect(view(lensIndex(0),
    set(
      lensIndex(0), 11, set(
        lensIndex(0), 10, testList
      )
    ))).toBe(11)
})

---------------

lensPath

lensPath<S, K0 extends keyof S = keyof S>(path: [K0]): Lens<S, S[K0]>

It returns a lens that focuses on specified path.

const lensPath = R.lensPath(['x', 0, 'y'])
const input = {x: [{y: 2, z: 3}, {y: 4, z: 5}]}

R.view(lensPath, input) // => 2

R.set(lensPath, 1, input) 
// => {x: [{y: 1, z: 3}, {y: 4, z: 5}]}

R.over(xHeadYLens, R.negate, input) 
// => {x: [{y: -2, z: 3}, {y: 4, z: 5}]}

Try this R.lensPath example in Rambda REPL

All TypeScript definitions
lensPath<S, K0 extends keyof S = keyof S>(path: [K0]): Lens<S, S[K0]>;
lensPath<S, K0 extends keyof S = keyof S, K1 extends keyof S[K0] = keyof S[K0]>(
  path: [K0, K1],
): Lens<S, S[K0][K1]>;
lensPath<
  S,
  K0 extends keyof S = keyof S,
  K1 extends keyof S[K0] = keyof S[K0],
  K2 extends keyof S[K0][K1] = keyof S[K0][K1]
>(path: [K0, K1, K2]): Lens<S, S[K0][K1][K2]>;
lensPath<
  S,
  K0 extends keyof S = keyof S,
  K1 extends keyof S[K0] = keyof S[K0],
  K2 extends keyof S[K0][K1] = keyof S[K0][K1],
  K3 extends keyof S[K0][K1][K2] = keyof S[K0][K1][K2]
>(path: [K0, K1, K2, K3]): Lens<S, S[K0][K1][K2][K3]>;
lensPath<
  S,
  K0 extends keyof S = keyof S,
  K1 extends keyof S[K0] = keyof S[K0],
  K2 extends keyof S[K0][K1] = keyof S[K0][K1],
  K3 extends keyof S[K0][K1][K2] = keyof S[K0][K1][K2],
  K4 extends keyof S[K0][K1][K2][K3] = keyof S[K0][K1][K2][K3]
>(path: [K0, K1, K2, K3, K4]): Lens<S, S[K0][K1][K2][K3][K4]>;
lensPath<
  S,
  K0 extends keyof S = keyof S,
  K1 extends keyof S[K0] = keyof S[K0],
  K2 extends keyof S[K0][K1] = keyof S[K0][K1],
  K3 extends keyof S[K0][K1][K2] = keyof S[K0][K1][K2],
  K4 extends keyof S[K0][K1][K2][K3] = keyof S[K0][K1][K2][K3],
  K5 extends keyof S[K0][K1][K2][K3][K4] = keyof S[K0][K1][K2][K3][K4]
>(path: [K0, K1, K2, K3, K4, K5]): Lens<S, S[K0][K1][K2][K3][K4][K5]>;
lensPath<S = any, A = any>(path: Path): Lens<S, A>;
R.lensPath source
import { assocPath } from './assocPath.js'
import { lens } from './lens.js'
import { path } from './path.js'

export function lensPath(key){
  return lens(path(key), assocPath(key))
}
Tests
import { compose } from './compose.js'
import { identity } from './identity.js'
import { inc } from './inc.js'
import { lensPath } from './lensPath.js'
import { lensProp } from './lensProp.js'
import { over } from './over.js'
import { set } from './set.js'
import { view } from './view.js'

const testObj = {
  a : [ { b : 1 }, { b : 2 } ],
  d : 3,
}

test('view', () => {
  expect(view(lensPath('d'), testObj)).toBe(3)
  expect(view(lensPath('a.0.b'), testObj)).toBe(1)
  // this is different to ramda, as ramda will return a clone of the input object
  expect(view(lensPath(''), testObj)).toBeUndefined()
})

test('set', () => {
  expect(set(
    lensProp('d'), 0, testObj
  )).toEqual({
    a : [ { b : 1 }, { b : 2 } ],
    d : 0,
  })
  expect(set(
    lensPath('a.0.b'), 0, testObj
  )).toEqual({
    a : [ { b : 0 }, { b : 2 } ],
    d : 3,
  })
  expect(set(
    lensPath('a.0.X'), 0, testObj
  )).toEqual({
    a : [
      {
        b : 1,
        X : 0,
      },
      { b : 2 },
    ],
    d : 3,
  })
  expect(set(
    lensPath([]), 0, testObj
  )).toBe(0)
})

test('over', () => {
  expect(over(
    lensPath('d'), inc, testObj
  )).toEqual({
    a : [ { b : 1 }, { b : 2 } ],
    d : 4,
  })
  expect(over(
    lensPath('a.1.b'), inc, testObj
  )).toEqual({
    a : [ { b : 1 }, { b : 3 } ],
    d : 3,
  })
  expect(over(
    lensProp('X'), identity, testObj
  )).toEqual({
    a : [ { b : 1 }, { b : 2 } ],
    d : 3,
    X : undefined,
  })
  expect(over(
    lensPath('a.0.X'), identity, testObj
  )).toEqual({
    a : [
      {
        b : 1,
        X : undefined,
      },
      { b : 2 },
    ],
    d : 3,
  })
})

test('compose', () => {
  const composedLens = compose(lensPath('a'), lensPath('1.b'))
  expect(view(composedLens, testObj)).toBe(2)
})

test('set s (get s) === s', () => {
  expect(set(
    lensPath([ 'd' ]), view(lensPath([ 'd' ]), testObj), testObj
  )).toEqual(testObj)
  expect(set(
    lensPath([ 'a', 0, 'b' ]),
    view(lensPath([ 'a', 0, 'b' ]), testObj),
    testObj
  )).toEqual(testObj)
})

test('get (set s v) === v', () => {
  expect(view(lensPath([ 'd' ]), set(
    lensPath([ 'd' ]), 0, testObj
  ))).toBe(0)
  expect(view(lensPath([ 'a', 0, 'b' ]), set(
    lensPath([ 'a', 0, 'b' ]), 0, testObj
  ))).toBe(0)
})

test('get (set(set s v1) v2) === v2', () => {
  const p = [ 'd' ]
  const q = [ 'a', 0, 'b' ]
  expect(view(lensPath(p), set(
    lensPath(p), 11, set(
      lensPath(p), 10, testObj
    )
  ))).toBe(11)
  expect(view(lensPath(q), set(
    lensPath(q), 11, set(
      lensPath(q), 10, testObj
    )
  ))).toBe(11)
})

---------------

lensProp

lensProp<S, K extends keyof S = keyof S>(prop: K): Lens<S, S[K]>

It returns a lens that focuses on specified property prop.

const xLens = R.lensProp('x');
const input = {x: 1, y: 2}

R.view(xLens, input) // => 1

R.set(xLens, 4, input) 
// => {x: 4, y: 2}

R.over(xLens, R.negate, input) 
// => {x: -1, y: 2}

Try this R.lensProp example in Rambda REPL

All TypeScript definitions
lensProp<S, K extends keyof S = keyof S>(prop: K): Lens<S, S[K]>;
R.lensProp source
import { assoc } from './assoc.js'
import { lens } from './lens.js'
import { prop } from './prop.js'

export function lensProp(key){
  return lens(prop(key), assoc(key))
}
Tests
import { compose } from './compose.js'
import { identity } from './identity.js'
import { inc } from './inc.js'
import { lensProp } from './lensProp.js'
import { over } from './over.js'
import { set } from './set.js'
import { view } from './view.js'

const testObj = {
  a : 1,
  b : 2,
  c : 3,
}

test('focuses object the specified object property', () => {
  expect(view(lensProp('a'), testObj)).toBe(1)
})

test('returns undefined if the specified property does not exist', () => {
  expect(view(lensProp('X'), testObj)).toBeUndefined()
})

test('sets the value of the object property specified', () => {
  expect(set(
    lensProp('a'), 0, testObj
  )).toEqual({
    a : 0,
    b : 2,
    c : 3,
  })
})

test('adds the property to the object if it doesn\'t exist', () => {
  expect(set(
    lensProp('d'), 4, testObj
  )).toEqual({
    a : 1,
    b : 2,
    c : 3,
    d : 4,
  })
})

test('applies function to the value of the specified object property', () => {
  expect(over(
    lensProp('a'), inc, testObj
  )).toEqual({
    a : 2,
    b : 2,
    c : 3,
  })
})

test('applies function to undefined and adds the property if it doesn\'t exist', () => {
  expect(over(
    lensProp('X'), identity, testObj
  )).toEqual({
    a : 1,
    b : 2,
    c : 3,
    X : undefined,
  })
})

test('can be composed', () => {
  const nestedObj = {
    a : { b : 1 },
    c : 2,
  }
  const composedLens = compose(lensProp('a'), lensProp('b'))

  expect(view(composedLens, nestedObj)).toBe(1)
})

test('set s (get s) === s', () => {
  expect(set(
    lensProp('a'), view(lensProp('a'), testObj), testObj
  )).toEqual(testObj)
})

test('get (set s v) === v', () => {
  expect(view(lensProp('a'), set(
    lensProp('a'), 0, testObj
  ))).toBe(0)
})

test('get (set(set s v1) v2) === v2', () => {
  expect(view(lensProp('a'),
    set(
      lensProp('a'), 11, set(
        lensProp('a'), 10, testObj
      )
    ))).toBe(11)
})

---------------

lensSatisfies

lensSatisfies<PredicateInput, Input>(predicate: (x: PredicateInput) => boolean, lens: Lens<PredicateInput, Input>, input: Input): boolean

It returns true if data structure focused by the given lens satisfies the predicate.

💥 Idea for this method comes from ramda-adjunct library

const fn = R.lensSatisfies(x => x > 5, R.lensIndex(0))
const result = [
  fn([10, 20, 30]),
  fn([1, 2, 3]),
]
// => [true, false]

Try this R.lensSatisfies example in Rambda REPL

All TypeScript definitions
lensSatisfies<PredicateInput, Input>(predicate: (x: PredicateInput) => boolean, lens: Lens<PredicateInput, Input>, input: Input): boolean;
lensSatisfies<PredicateInput, Input>(predicate: (x: PredicateInput) => boolean, lens: Lens<PredicateInput, Input>): (input: Input) => boolean;
lensSatisfies<T>(predicate: (x: T) => boolean, lens: Lens<T[], T>, input: T[]): boolean;
lensSatisfies<T>(predicate: (x: T) => boolean, lens: Lens<T[], T>): (input: T[]) => boolean;
R.lensSatisfies source
import { curry } from './curry.js'
import { view } from './view.js'

function lensSatisfiesFn(
  predicate, lens, input
){
  return Boolean(predicate(view(lens, input)))
}

export const lensSatisfies = curry(lensSatisfiesFn)
Tests
import { lensIndex } from './lensIndex.js'
import { lensPath } from './lensPath.js'
import { lensSatisfies } from './lensSatisfies.js'

const predicate = x => x > 1

test('with list', () => {
  const lens = lensIndex(0)
  const fn = lensSatisfies(predicate, lens)
  expect(fn([ 10, 20, 30 ])).toBeTrue()
  expect(fn([ 1, 2, 3 ])).toBeFalse()
})

test('with R.lensPath', () => {
  const input1 = { a : { b : 10 } }
  const input2 = { a : { b : 1 } }
  const lens = lensPath('a.b')
  const fn = lensSatisfies(predicate, lens)

  expect(fn(input1)).toBeTrue()
  expect(fn(input2)).toBeFalse()
})

---------------

lt

lt<T, U>(x: T, y: U): boolean
const result = [R.lt(2, 1), R.lt(2, 3)]
// => [false, true]

Try this R.lt example in Rambda REPL

All TypeScript definitions
lt<T, U>(x: T, y: U): boolean;
lt<T, U>(x: T): (y: U) => boolean;
R.lt source
export function lt(a, b){
  if (arguments.length === 1)
    return _b => lt(a, _b)

  return a < b
}

---------------

lte

lte<T, U>(x: T, y: U): boolean
const result = [R.lte(2, 1), R.lte(2, 2), R.lte(2, 3)]
// => [false, true, true]

Try this R.lte example in Rambda REPL

All TypeScript definitions
lte<T, U>(x: T, y: U): boolean;
lte<T, U>(x: T): (y: U) => boolean;
R.lte source
export function lte(a, b){
  if (arguments.length === 1)
    return _b => lte(a, _b)

  return a <= b
}

---------------

map

map<T, U>(fn: ObjectIterator<T, U>, iterable: Dictionary<T>): Dictionary<U>

It returns the result of looping through iterable with fn.

It works with both array and object.

💥 Unlike Ramda's map, here property and input object are passed as arguments to fn, when iterable is an object.

const fn = x => x * 2
const fnWhenObject = (val, prop)=>{
  return `${prop}-${val}`
}

const iterable = [1, 2]
const obj = {a: 1, b: 2}

const result = [ 
  R.map(fn, iterable),
  R.map(fnWhenObject, obj)
]
// => [ [2, 4], {a: 'a-1', b: 'b-2'}]

Try this R.map example in Rambda REPL

All TypeScript definitions
map<T, U>(fn: ObjectIterator<T, U>, iterable: Dictionary<T>): Dictionary<U>;
map<T, U>(fn: Iterator<T, U>, iterable: T[]): U[];
map<T, U>(fn: Iterator<T, U>): (iterable: T[]) => U[];
map<T, U, S>(fn: ObjectIterator<T, U>): (iterable: Dictionary<T>) => Dictionary<U>;
map<T>(fn: Iterator<T, T>): (iterable: T[]) => T[];
map<T>(fn: Iterator<T, T>, iterable: T[]): T[];
R.map source
import { INCORRECT_ITERABLE_INPUT } from './_internals/constants.js'
import { isArray } from './_internals/isArray.js'
import { keys } from './_internals/keys.js'

export function mapArray(
  fn, list, isIndexed = false
){
  let index = 0
  const willReturn = Array(list.length)

  while (index < list.length){
    willReturn[ index ] = isIndexed ? fn(list[ index ], index) : fn(list[ index ])

    index++
  }

  return willReturn
}

export function mapObject(fn, obj){
  if (arguments.length === 1){
    return _obj => mapObject(fn, _obj)
  }
  let index = 0
  const objKeys = keys(obj)
  const len = objKeys.length
  const willReturn = {}

  while (index < len){
    const key = objKeys[ index ]
    willReturn[ key ] = fn(
      obj[ key ], key, obj
    )
    index++
  }

  return willReturn
}

export const mapObjIndexed = mapObject

export function map(fn, iterable){
  if (arguments.length === 1) return _iterable => map(fn, _iterable)
  if (!iterable){
    throw new Error(INCORRECT_ITERABLE_INPUT)
  }

  if (isArray(iterable)) return mapArray(fn, iterable)

  return mapObject(fn, iterable)
}
Tests
import { map as mapRamda } from 'ramda'

import { map } from './map.js'

const double = x => x * 2

describe('with array', () => {
  it('happy', () => {
    expect(map(double, [ 1, 2, 3 ])).toEqual([ 2, 4, 6 ])
  })

  it('curried', () => {
    expect(map(double)([ 1, 2, 3 ])).toEqual([ 2, 4, 6 ])
  })
})

describe('with object', () => {
  const obj = {
    a : 1,
    b : 2,
  }

  it('happy', () => {
    expect(map(double, obj)).toEqual({
      a : 2,
      b : 4,
    })
  })

  it('property as second and input object as third argument', () => {
    const obj = {
      a : 1,
      b : 2,
    }
    const iterator = (
      val, prop, inputObject
    ) => {
      expect(prop).toBeString()
      expect(inputObject).toEqual(obj)

      return val * 2
    }

    expect(map(iterator)(obj)).toEqual({
      a : 2,
      b : 4,
    })
  })
})

test('bad inputs difference between Ramda and Rambda', () => {
  expect(() => map(double, null)).toThrowErrorMatchingInlineSnapshot('"Incorrect iterable input"')
  expect(() => map(double)(undefined)).toThrowErrorMatchingInlineSnapshot('"Incorrect iterable input"')
  expect(() => mapRamda(double, null)).toThrowErrorMatchingInlineSnapshot('"Cannot read properties of null (reading \'fantasy-land/map\')"')
  expect(() =>
    mapRamda(double, undefined)).toThrowErrorMatchingInlineSnapshot('"Cannot read properties of undefined (reading \'fantasy-land/map\')"')
})

---------------

mapArray

mapArray<T>(fn: Iterator<T, T>, iterable: T[]): T[]
const result = R.mapArray(x => x + 1, [1, 2])
// => [2, 3]

Try this R.mapArray example in Rambda REPL

All TypeScript definitions
mapArray<T>(fn: Iterator<T, T>, iterable: T[]): T[];
mapArray<T, U>(fn: Iterator<T, U>, iterable: T[]): U[];
mapArray<T, U>(fn: Iterator<T, U>): (iterable: T[]) => U[];
mapArray<T>(fn: Iterator<T, T>): (iterable: T[]) => T[];

---------------

mapAsync

mapAsync<T, K>(fn: AsyncIterable<T, K>, list: T[]): Promise<K[]>

Sequential asynchronous mapping with fn over members of list.

async function fn(x){
  await R.delay(1000)

  return x+1
}

const result = await R.mapAsync(fn, [1, 2, 3])
// `result` resolves after 3 seconds to `[2, 3, 4]`

Try this R.mapAsync example in Rambda REPL

All TypeScript definitions
mapAsync<T, K>(fn: AsyncIterable<T, K>, list: T[]): Promise<K[]>;
mapAsync<T, K>(fn: AsyncIterableIndexed<T, K>, list: T[]): Promise<K[]>;
mapAsync<T, K>(fn: AsyncIterable<T, K>) : ( list: T[]) => Promise<K[]>;
mapAsync<T, K>(fn: AsyncIterableIndexed<T, K>) : ( list: T[]) => Promise<K[]>;
R.mapAsync source
import { isArray } from './_internals/isArray.js'

async function mapAsyncFn(fn, listOrObject){
  if (isArray(listOrObject)){
    const willReturn = []
    let i = 0
    for (const a of listOrObject){
      willReturn.push(await fn(a, i++))
    }

    return willReturn
  }

  const willReturn = {}
  for (const prop in listOrObject){
    willReturn[ prop ] = await fn(listOrObject[ prop ], prop)
  }

  return willReturn
}

export function mapAsync(fn, listOrObject){
  if (arguments.length === 1){
    return async _listOrObject => mapAsyncFn(fn, _listOrObject)
  }

  return new Promise((resolve, reject) => {
    mapAsyncFn(fn, listOrObject).then(resolve)
      .catch(reject)
  })
}
Tests
import { composeAsync } from './composeAsync.js'
import { delay } from './delay.js'
import { map } from './map.js'
import { mapAsync } from './mapAsync.js'

const rejectDelay = a =>
  new Promise((_, reject) => {
    setTimeout(() => {
      reject(a + 20)
    }, 100)
  })

test('happy', async () => {
  const fn = async (x, prop) => {
    await delay(100)
    expect(prop).toBeNumber()

    return x + 1
  }
  const result = await mapAsync(fn, [ 1, 2, 3 ])
  expect(result).toEqual([ 2, 3, 4 ])
})

test('with object', async () => {
  const fn = async (x, prop) => {
    expect(prop).toBeString()

    return x + 1
  }
  const result = await mapAsync(fn, {
    a : 1,
    b : 2,
  })
  expect(result).toEqual({
    a : 2,
    b : 3,
  })
})

test('with R.composeAsync', async () => {
  const result = await composeAsync(
    map(x => x + 1),
    mapAsync(async x => {
      delay(x)

      return x
    }),
    map(x => x * 10)
  )([ 1, 2, 3 ])
  expect(result).toEqual([ 11, 21, 31 ])
})

test('error', async () => {
  try {
    await mapAsync(rejectDelay)([ 1, 2, 3 ])
  } catch (err){
    expect(err).toBe(21)
  }
})

---------------

mapcat

mapcat<T>(x: T): T
const result = R.mapcat()
// =>

Try this R.mapcat example in Rambda REPL

All TypeScript definitions
mapcat<T>(x: T): T;
R.mapcat source
export function mapcat(tranformFn, listOfLists){
  if (arguments.length === 1){
    return _listOfLists => mapcat(tranformFn, _listOfLists)
  }

  let willReturn = []
  const intermediateResult = listOfLists.map(list =>
    list.map(x => tranformFn(x)))

  intermediateResult.forEach(transformedList => {
    willReturn = [ ...willReturn, ...transformedList ]
  })

  return willReturn
}
Tests
import { mapcat } from './mapcat.js'

test('happy', () => {
  const result = mapcat(x => x.toUpperCase(),
    [
      [ 'a', 'b' ],
      [ 'c', 'd' ],
      [ 'e', 'f' ],
    ])
  console.log(result)
})

---------------

mapIndexed

mapIndexed<T, U>(fn: ObjectIterator<T, U>, iterable: Dictionary<T>): Dictionary<U>

Same as R.map, but it passes index as second argument to the iterator, when looping over arrays.

All TypeScript definitions
mapIndexed<T, U>(fn: ObjectIterator<T, U>, iterable: Dictionary<T>): Dictionary<U>;
mapIndexed<T, U>(fn: IndexedIterator<T, U>, iterable: T[]): U[];
mapIndexed<T, U>(fn: IndexedIterator<T, U>): (iterable: T[]) => U[];
mapIndexed<T, U, S>(fn: ObjectIterator<T, U>): (iterable: Dictionary<T>) => Dictionary<U>;
mapIndexed<T>(fn: IndexedIterator<T, T>): (iterable: T[]) => T[];
mapIndexed<T>(fn: IndexedIterator<T, T>, iterable: T[]): T[];
R.mapIndexed source
import { isArray } from './_internals/isArray.js'
import { mapArray, mapObject } from './map.js'

export function mapIndexed(fn, iterable){
  if (arguments.length === 1){
    return _iterable => mapIndexed(fn, _iterable)
  }
  if (iterable === undefined) return []
  if (isArray(iterable)) return mapArray(
    fn, iterable, true
  )

  return mapObject(fn, iterable)
}
Tests
import { map } from './map.js'
import { mapIndexed } from './mapIndexed.js'

const iterator = (x, i) => {
  expect(x).toBeNumber()
  expect(i).toBeNumber()
}

test('happy', () => {
  const list = [ 1, 2, 3 ]
  mapIndexed(iterator, list)
  mapIndexed(iterator)(list)
})

test('with object', () => {
  const iterator = x => x + 1
  const obj = { a : 1 }
  expect(mapIndexed(iterator, obj)).toEqual(map(iterator, obj))
})

test('with bad input', () => {
  expect(mapIndexed(iterator, undefined)).toEqual([])
})

---------------

mapKeys

mapKeys<T, U>(changeKeyFn: (x: string) => string, obj: { [key: string]: T}): U

It takes an object and returns a new object with changed keys according to changeKeyFn function.

const obj = {a: 1, b: 2}
const changeKeyFn = prop => `{prop}_foo`
const result = R.mapKeys(changeKeyFn, Record<string, unknown>)
// => {a_foo: 1, b_foo: 2}

Try this R.mapKeys example in Rambda REPL

All TypeScript definitions
mapKeys<T, U>(changeKeyFn: (x: string) => string, obj: { [key: string]: T}): U;
mapKeys<T, U>(changeKeyFn: (x: string) => string): (obj: { [key: string]: T}) => U;
R.mapKeys source
export function mapKeys(changeKeyFn, obj){
  if (arguments.length === 1) return _obj => mapKeys(changeKeyFn, _obj)
  const toReturn = {}

  Object.keys(obj).forEach(prop => toReturn[ changeKeyFn(prop) ] = obj[ prop ])

  return toReturn
}
Tests
import { mapKeys } from './mapKeys.js'

const obj = {
  a : 1,
  b : 2,
}
const changeKeyFn = prop => `${ prop }_foo`
const expected = {
  a_foo : 1,
  b_foo : 2,
}

test('happy', () => {
  const result = mapKeys(changeKeyFn, obj)

  expect(result).toEqual(expected)
})

test('curried', () => {
  const result = mapKeys(changeKeyFn)(obj)

  expect(result).toEqual(expected)
})

---------------

mapObject

mapObject<T>(fn: ObjectIterator<T, T>, iterable: Dictionary<T>): Dictionary<T>
const result = R.mapObject(x => x + 1, {a:1, b:2})
// => {a:2, b:3}

Try this R.mapObject example in Rambda REPL

All TypeScript definitions
mapObject<T>(fn: ObjectIterator<T, T>, iterable: Dictionary<T>): Dictionary<T>;
mapObject<T, U>(fn: ObjectIterator<T, U>, iterable: Dictionary<T>): Dictionary<U>;
mapObject<T>(fn: ObjectIterator<T, T>): (iterable: Dictionary<T>) => Dictionary<T>;
mapObject<T, U>(fn: ObjectIterator<T, U>): (iterable: Dictionary<T>) => Dictionary<U>;

---------------

mapObjIndexed

mapObjIndexed<T>(fn: ObjectIterator<T, T>, iterable: Dictionary<T>): Dictionary<T>

It works the same way as R.map does for objects. It is added as Ramda also has this method.

const fn = (val, prop) => {
  return `${prop}-${val}`
}

const obj = {a: 1, b: 2}

const result = R.mapObjIndexed(fn, obj)
// => {a: 'a-1', b: 'b-2'}

Try this R.mapObjIndexed example in Rambda REPL

All TypeScript definitions
mapObjIndexed<T>(fn: ObjectIterator<T, T>, iterable: Dictionary<T>): Dictionary<T>;
mapObjIndexed<T, U>(fn: ObjectIterator<T, U>, iterable: Dictionary<T>): Dictionary<U>;
mapObjIndexed<T>(fn: ObjectIterator<T, T>): (iterable: Dictionary<T>) => Dictionary<T>;
mapObjIndexed<T, U>(fn: ObjectIterator<T, U>): (iterable: Dictionary<T>) => Dictionary<U>;

---------------

mapParallelAsync

mapParallelAsync<T, K>(fn: AsyncIterable<T, K>, list: T[]): Promise<K[]>

Parallel asynchronous mapping with fn over members of list.

async function fn(x){
  await R.delay(1000)

  return x+1
}

const result = await R.mapParallelAsync(fn, [1, 2, 3])
// `result` resolves after 1 second to `[2, 3, 4]`

Try this R.mapParallelAsync example in Rambda REPL

All TypeScript definitions
mapParallelAsync<T, K>(fn: AsyncIterable<T, K>, list: T[]): Promise<K[]>;
mapParallelAsync<T, K>(fn: AsyncIterableIndexed<T, K>, list: T[]): Promise<K[]>;
mapParallelAsync<T, K>(fn: AsyncIterable<T, K>) : ( list: T[]) => Promise<K[]>;
mapParallelAsync<T, K>(fn: AsyncIterableIndexed<T, K>) : ( list: T[]) => Promise<K[]>;
R.mapParallelAsync source
export async function mapParallelAsyncFn(fn, arr){
  const promised = arr.map((a, i) => fn(a, i))

  return Promise.all(promised)
}

export function mapParallelAsync(fn, arr){
  if (arguments.length === 1){
    return async holder => mapParallelAsyncFn(fn, holder)
  }

  return new Promise((resolve, reject) => {
    mapParallelAsyncFn(fn, arr).then(resolve)
      .catch(reject)
  })
}
Tests
import { willFailAssertion } from './_internals/testUtils.js'
import { composeAsync } from './composeAsync.js'
import { delay } from './delay.js'
import { map } from './map.js'
import { mapParallelAsync } from './mapParallelAsync.js'

test('happy', async () => {
  const fn = async x => {
    await delay(100)

    return x + 10
  }
  const result = await mapParallelAsync(fn, [ 1, 2, 3 ])
  expect(result).toEqual([ 11, 12, 13 ])
})

test('composeAsync', async () => {
  const result = await composeAsync(
    mapParallelAsync(async x => {
      await delay(100)

      return x + 1
    }),
    mapParallelAsync(async x => {
      await delay(100)

      return x + 10
    }),
    map(x => x * 10)
  )([ 1, 2, 3 ])
  expect(result).toEqual([ 21, 31, 41 ])
})

test('error', async () => {
  try {
    const fn = async () => {
      JSON.parse('{:')
    }
    await mapParallelAsync(fn, [ 1, 2, 3 ])
    willFailAssertion()
  } catch (err){
    expect(err.message).toBeTruthy()
  }
})

test('pass index as second argument', async () => {
  await mapParallelAsync((x, i) => {
    expect(x % 10).toBe(0)
    expect(typeof i).toBe('number')
  },
  [ 10, 20, 30 ])
})

---------------

mapParallelAsyncWithLimit

mapParallelAsyncWithLimit<T, K>(fn: AsyncIterable<T, K>, limit: number, list: T[]): Promise<K[]>

It is similar to R.mapParallelAsync in that it uses Promise.all, but not over the whole list, rather than with only slice from list with length limit.

💥 For example usage, please check R.mapAsyncLimit tests.

All TypeScript definitions
mapParallelAsyncWithLimit<T, K>(fn: AsyncIterable<T, K>, limit: number, list: T[]): Promise<K[]>;
mapParallelAsyncWithLimit<T, K>(fn: AsyncIterable<T, K>, limit: number): (list: T[]) => Promise<K[]>;
mapParallelAsyncWithLimit<T, K>(fn: AsyncIterableIndexed<T, K>, limit: number, list: T[]): Promise<K[]>;
mapParallelAsyncWithLimit<T, K>(fn: AsyncIterableIndexed<T, K>, limit: number): (list: T[]) => Promise<K[]>;
R.mapParallelAsyncWithLimit source
import { mapParallelAsync, mapParallelAsyncFn } from './mapParallelAsync.js'
import { splitEvery } from './splitEvery.js'

async function mapParallelAsyncWithLimitFn(
  iterable, limit, list
){
  if (list.length < limit) return mapParallelAsync(iterable, list)

  const slices = splitEvery(limit, list)

  let toReturn = []
  for (const slice of slices){
    const iterableResult = await mapParallelAsyncFn(iterable, slice)
    toReturn = [ ...toReturn, ...iterableResult ]
  }

  return toReturn
}

export function mapParallelAsyncWithLimit(
  iterable, limit, list
){
  if (arguments.length === 2){
    return async _list => mapParallelAsyncWithLimitFn(
      iterable, limit, _list
    )
  }

  return new Promise((resolve, reject) => {
    mapParallelAsyncWithLimitFn(
      iterable, limit, list
    )
      .then(resolve)
      .catch(reject)
  })
}
Tests
import isCI from 'is-ci'

import { composeAsync } from './composeAsync.js'
import { delay } from './delay.js'
import { mapAsync } from './mapAsync.js'
import { mapParallelAsyncWithLimit } from './mapParallelAsyncWithLimit.js'
import { toDecimal } from './toDecimal.js'

jest.setTimeout(30000)

test('happy', async () => {
  const limit = 3
  const startTime = new Date().getTime()
  const list = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
  const iterable = async x => {
    await delay(500)

    return x + 1
  }
  const result = await mapParallelAsyncWithLimit(
    iterable, limit, list
  )
  const endTime = new Date().getTime()
  const diffTime = endTime - startTime

  const startTime2 = new Date().getTime()
  await mapAsync(iterable, list)
  const endTime2 = new Date().getTime()
  const diffTime2 = endTime2 - startTime2

  const methodScale = toDecimal((diffTime2 - diffTime) / 1000, 0)
  expect(result).toEqual([ 2, 3, 4, 5, 6, 7, 8, 9, 10 ])
  if (!isCI) expect(methodScale).toBe(limit)
})

const fn = async x => {
  await delay(100)

  return x + 1
}

test('with R.composeAsync', async () => {
  const result = await composeAsync(mapParallelAsyncWithLimit(fn, 2), x =>
    x.map(xx => xx + 1))([ 1, 2, 3, 4, 5, 6 ])
  expect(result).toEqual([ 3, 4, 5, 6, 7, 8 ])
})

test('fallback to R.mapFastAsync', async () => {
  const result = await mapParallelAsyncWithLimit(
    fn, 4, [ 1, 2, 3 ]
  )
  expect(result).toEqual([ 2, 3, 4 ])
})

---------------

mapToObject

mapToObject<T, U extends object>(fn: (input: T) => U|false, list: readonly T[]): U

This method allows to generate an object from a list using input function fn.

This function must return either an object or false for every member of list input.

If false is returned, then this element of list will be skipped in the calculation of the result.

All of returned objects will be merged to generate the final result.

const list = [1, 2, 3, 12]
const fn = x => {
  if(x > 10) return false
  return x % 2 ? {[x]: x + 1}: {[x]: x + 10}
}

const result = mapToObject(fn, list)
const expected = {'1': 2, '2': 12, '3': 4}
// => `result` is equal to `expected`

Try this R.mapToObject example in Rambda REPL

All TypeScript definitions
mapToObject<T, U extends object>(fn: (input: T) => U|false, list: readonly T[]): U;
mapToObject<T, U extends object>(fn: (input: T) => U|false): (list: readonly T[]) => U;
mapToObject<T, U>(fn: (input: T) => object|false, list: T[]): U;
mapToObject<T, U>(fn: (input: T) => object|false): (list: T[]) => U;
R.mapToObject source
import { map } from './map.js'
import { mergeAll } from './mergeAll.js'
import { ok } from './ok.js'
import { type } from './type.js'

export function mapToObject(fn, list){
  if (arguments.length === 1){
    return listHolder => mapToObject(fn, listHolder)
  }
  ok(type(fn), type(list))('Function', 'Array')

  return mergeAll(map(fn, list))
}
Tests
import { mapToObject } from './mapToObject.js'

const list = [ 1, 2, 3 ]
const fn = x => x % 2 ? { [ x ] : x + 1 } : { [ x ] : x + 10 }
const expected = {
  1 : 2,
  2 : 12,
  3 : 4,
}

test('happy', () => {
  const result = mapToObject(fn, list)
  expect(result).toEqual(expected)
})

test('curried', () => {
  const result = mapToObject(fn)(list)
  expect(result).toEqual(expected)
})

test('string.fn test', () => {
  const list = [ 'auto', 'bar=false', 'foo', 'baz=1.5', 's=more', 'k=2' ]
  const fn = x => {
    const [ key, value ] = x.split('=')
    if (value === undefined || value === 'true'){
      return { [ key ] : true }
    }
    if (value === 'false'){
      return { [ key ] : false }
    }

    if (Number.isNaN(Number(value))){
      return { [ key ] : value }
    }

    return { [ key ] : Number(value) }
  }

  const expectedResult = {
    auto : true,
    foo  : true,
    bar  : false,
    baz  : 1.5,
    s    : 'more',
    k    : 2,
  }
  const result = mapToObject(fn, list)

  expect(result).toEqual(expectedResult)
})

test('bad path', () => {
  expect(() => mapToObject(1, null)).toThrowErrorMatchingInlineSnapshot(`
    "Failed R.ok -
    reason: {"input":"Number","schema":"Function"}
    all inputs: ["Number","Null"]
    all schemas: ["Function","Array"]"
  `)
})

---------------

mapToObjectAsync

mapToObjectAsync<T, U extends object>(fn: (input: T) => Promise<U|false>, list: readonly T[]): Promise<U>

Asynchronous version of R.mapToObject

All TypeScript definitions
mapToObjectAsync<T, U extends object>(fn: (input: T) => Promise<U|false>, list: readonly T[]): Promise<U>;
mapToObjectAsync<T, U extends object>(fn: (input: T) => Promise<U|false>): (list: readonly T[]) => Promise<U>;
mapToObjectAsync<T, U>(fn: (input: T) => object|false, list: T[]): U;
mapToObjectAsync<T, U>(fn: (input: T) => object|false): (list: T[]) => U;
R.mapToObjectAsync source
import { mapAsync } from './mapAsync.js'

export async function mapToObjectAsyncFn(fn, list){
  let toReturn = {}

  const innerIterable = async x => {
    const intermediateResult = await fn(x)
    if (intermediateResult === false) return
    toReturn = {
      ...toReturn,
      ...intermediateResult,
    }
  }

  await mapAsync(innerIterable, list)

  return toReturn
}

export function mapToObjectAsync(fn, list){
  if (arguments.length === 1){
    return async _list => mapToObjectAsyncFn(fn, _list)
  }

  return new Promise((resolve, reject) => {
    mapToObjectAsyncFn(fn, list).then(resolve)
      .catch(reject)
  })
}
Tests
import { composeAsync } from './composeAsync.js'
import { delay } from './delay.js'
import { mapToObjectAsync } from './mapToObjectAsync.js'

const list = [ 1, 2, 3, 12 ]
const fn = async x => {
  await delay(100)
  if (x > 10) return false

  return x % 2 ? { [ `key${ x }` ] : x + 1 } : { [ `key${ x }` ] : x + 10 }
}

const expected = {
  key1 : 2,
  key2 : 12,
  key3 : 4,
}

test('happy', async () => {
  const result = await mapToObjectAsync(fn, list)
  expect(result).toEqual(expected)
})

test('with R.composeAsync', async () => {
  const result = await composeAsync(mapToObjectAsync(fn), x =>
    x.filter(xx => xx > 1))(list)

  expect(result).toEqual({
    key2 : 12,
    key3 : 4,
  })
})

---------------

match

match(regExpression: RegExp, str: string): string[]

Curried version of String.prototype.match which returns empty array, when there is no match.

const result = [
  R.match('a', 'foo'),
  R.match(/([a-z]a)/g, 'bananas')
]
// => [[], ['ba', 'na', 'na']]

Try this R.match example in Rambda REPL

All TypeScript definitions
match(regExpression: RegExp, str: string): string[];
match(regExpression: RegExp): (str: string) => string[];
R.match source
export function match(pattern, input){
  if (arguments.length === 1) return _input => match(pattern, _input)

  const willReturn = input.match(pattern)

  return willReturn === null ? [] : willReturn
}
Tests
import { equals } from './equals.js'
import { match } from './match.js'

test('happy', () => {
  expect(match(/a./g)('foo bar baz')).toEqual([ 'ar', 'az' ])
})

test('fallback', () => {
  expect(match(/a./g)('foo')).toEqual([])
})

test('with string', () => {
  expect(match('a', 'foo')).toEqual([])
  expect(equals(match('o', 'foo'), [ 'o' ])).toBeTrue()
})

test('throwing', () => {
  expect(() => {
    match(/a./g, null)
  }).toThrowErrorMatchingInlineSnapshot('"Cannot read properties of null (reading \'match\')"')
})

---------------

mathMod

mathMod(x: number, y: number): number

R.mathMod behaves like the modulo operator should mathematically, unlike the % operator (and by extension, R.modulo). So while -17 % 5 is -2, mathMod(-17, 5) is 3.

💥 Explanation is taken from Ramda documentation site.

const result = [
  R.mathMod(-17, 5),
  R.mathMod(17, 5),
  R.mathMod(17, -5),  
  R.mathMod(17, 0)   
]
// => [3, 2, NaN, NaN]

Try this R.mathMod example in Rambda REPL

All TypeScript definitions
mathMod(x: number, y: number): number;
mathMod(x: number): (y: number) => number;
R.mathMod source
import { isInteger } from './_internals/isInteger.js'

export function mathMod(x, y){
  if (arguments.length === 1) return _y => mathMod(x, _y)
  if (!isInteger(x) || !isInteger(y) || y < 1) return NaN

  return (x % y + y) % y
}
Tests
import { mathMod } from './mathMod.js'

test('happy', () => {
  expect(mathMod(-17)(5)).toBe(3)
  expect(mathMod(17, 5)).toBe(2)
  expect(mathMod(17, -5)).toBeNaN()
  expect(mathMod(17, 0)).toBeNaN()
  expect(mathMod('17', 5)).toBeNaN()
  expect(mathMod({}, 2)).toBeNaN()
  expect(mathMod([], 2)).toBeNaN()
  expect(mathMod(Symbol(), 2)).toBeNaN()
})

---------------

max

max<T extends Ord>(x: T, y: T): T

It returns the greater value between x and y.

const result = [
  R.max(5, 7),  
  R.max('bar', 'foo'),  
]
// => [7, 'foo']

Try this R.max example in Rambda REPL

All TypeScript definitions
max<T extends Ord>(x: T, y: T): T;
max<T extends Ord>(x: T): (y: T) => T;
R.max source
export function max(x, y){
  if (arguments.length === 1) return _y => max(x, _y)

  return y > x ? y : x
}
Tests
import { max } from './max.js'

test('with number', () => {
  expect(max(2, 1)).toBe(2)
})

test('with string', () => {
  expect(max('foo')('bar')).toBe('foo')
  expect(max('bar')('baz')).toBe('baz')
})

---------------

maxBy

maxBy<T>(compareFn: (input: T) => Ord, x: T, y: T): T

It returns the greater value between x and y according to compareFn function.

const compareFn = Math.abs

R.maxBy(compareFn, 5, -7) // => -7

Try this R.maxBy example in Rambda REPL

All TypeScript definitions
maxBy<T>(compareFn: (input: T) => Ord, x: T, y: T): T;
maxBy<T>(compareFn: (input: T) => Ord, x: T): (y: T) => T;
maxBy<T>(compareFn: (input: T) => Ord): (x: T) => (y: T) => T;
R.maxBy source
import { curry } from './curry.js'

export function maxByFn(
  compareFn, x, y
){
  return compareFn(y) > compareFn(x) ? y : x
}

export const maxBy = curry(maxByFn)
Tests
import { maxBy } from './maxBy.js'

test('happy', () => {
  expect(maxBy(
    Math.abs, -5, 2
  )).toBe(-5)
})

test('curried', () => {
  expect(maxBy(Math.abs)(2, -5)).toBe(-5)
  expect(maxBy(Math.abs)(2)(-5)).toBe(-5)
})

---------------

maybe

maybe<T>(ifRule: boolean, whenIf: T | Func<T>, whenElse: T | Func<T>): T

It acts as ternary operator and it is helpful when we have nested ternaries.

All of the inputs can be either direct values or anonymous functions. This is helpful if we don't want to evaluate certain paths as we can wrap this logic in a function.

const x = 4
const y = 8

const ifRule = x > 2
const whenIf = y > 10 ? 3 : 7
const whenElse = () => {
  // just to show that it won't be evaluated
  return JSON.parse('{a:')
}

const result = R.maybe(
  ifRule,
  whenIf,
  whenElse,
)
// `result` is `7`

Try this R.maybe example in Rambda REPL

All TypeScript definitions
maybe<T>(ifRule: boolean, whenIf: T | Func<T>, whenElse: T | Func<T>): T;
maybe<T>(ifRule: VoidInputFunc<boolean>, whenIf: T | Func<T>, whenElse: T | Func<T>): T;
R.maybe source
import { type } from './type.js'

export function maybe(
  ifRule, whenIf, whenElse
){
  const whenIfInput =
    ifRule && type(whenIf) === 'Function' ? whenIf() : whenIf

  const whenElseInput =
    !ifRule && type(whenElse) === 'Function' ? whenElse() : whenElse

  return ifRule ? whenIfInput : whenElseInput
}
Tests
import { maybe } from './maybe.js'

const WHEN_IF = 'WHEN_IF'
const WHEN_ELSE = 'WHEN_ELSE'

test('prevent type error', () => {
  const x = 5
  const y = null
  const ifRule = x > 3

  const result = maybe(
    ifRule, WHEN_IF, () => y.a === 'foo'
  )

  expect(result).toBe(WHEN_IF)
})

test('whenElse is a function', () => {
  const x = 2
  const y = { a : 1 }
  const ifRule = x > 3

  const result = maybe(
    ifRule, WHEN_IF, () => y.a === 'foo'
  )

  expect(result).toBeFalse()
})

test('whenIf', () => {
  const x = 5
  const ifRule = x > 3

  const result = maybe(
    ifRule, WHEN_IF, WHEN_ELSE
  )

  expect(result).toBe(WHEN_IF)
})

test('whenIf is a function', () => {
  const x = 5
  const ifRule = () => x > 3

  const result = maybe(
    ifRule, () => WHEN_IF, WHEN_ELSE
  )

  expect(result).toBe(WHEN_IF)
})

test('whenElse', () => {
  const x = 1
  const ifRule = x > 3

  const result = maybe(
    ifRule, WHEN_IF, WHEN_ELSE
  )

  expect(result).toBe(WHEN_ELSE)
})

---------------

mean

mean(list: number[]): number

It returns the mean value of list input.

R.mean([ 2, 7 ])
// => 4.5

Try this R.mean example in Rambda REPL

All TypeScript definitions
mean(list: number[]): number;
R.mean source
import { sum } from './sum.js'

export function mean(list){
  return sum(list) / list.length
}
Tests
import { mean } from './mean.js'

test('happy', () => {
  expect(mean([ 2, 7 ])).toBe(4.5)
})

test('with NaN', () => {
  expect(mean([])).toBeNaN()
})

---------------

median

median(list: number[]): number

It returns the median value of list input.

R.median([ 7, 2, 10, 9 ]) // => 8

Try this R.median example in Rambda REPL

All TypeScript definitions
median(list: number[]): number;
R.median source
import { mean } from './mean.js'

export function median(list){
  const len = list.length
  if (len === 0) return NaN
  const width = 2 - len % 2
  const idx = (len - width) / 2

  return mean(Array.prototype.slice
    .call(list, 0)
    .sort((a, b) => {
      if (a === b) return 0

      return a < b ? -1 : 1
    })
    .slice(idx, idx + width))
}
Tests
import { median } from './median.js'

test('happy', () => {
  expect(median([ 2 ])).toBe(2)
  expect(median([ 7, 2, 10, 2, 9 ])).toBe(7)
})

test('with empty array', () => {
  expect(median([])).toBeNaN()
})

---------------

memoize

memoize<T, K extends any[]>(fn: (...inputs: K) => T): (...inputs: K) => T

When fn is called for a second time with the same input, then the cache result is returned instead of calling again fn.

let result = 0
const fn = (a,b) =>{
  result++

  return a + b
}
const memoized = R.memoize(fn)
memoized(1, 2)
memoized(1, 2)

// => `result` is equal to `1`

Try this R.memoize example in Rambda REPL

All TypeScript definitions
memoize<T, K extends any[]>(fn: (...inputs: K) => T): (...inputs: K) => T;
R.memoize source
import { compose } from './compose.js'
import { map } from './map.js'
import { replace } from './replace.js'
import { sort } from './sort.js'
import { take } from './take.js'
import { type } from './type.js'

const cache = {}

const normalizeObject = obj => {
  const sortFn = (a, b) => a > b ? 1 : -1
  const willReturn = {}
  compose(map(prop => willReturn[ prop ] = obj[ prop ]),
    sort(sortFn))(Object.keys(obj))

  return willReturn
}

const stringify = a => {
  const aType = type(a)
  if (aType === 'String'){
    return a
  } else if ([ 'Function', 'Promise' ].includes(aType)){
    const compacted = replace(
      /\s{1,}/g, ' ', a.toString()
    )

    return replace(
      /\s/g, '_', take(15, compacted)
    )
  } else if (aType === 'Object'){
    return JSON.stringify(normalizeObject(a))
  }

  return JSON.stringify(a)
}

const generateProp = (fn, ...inputArguments) => {
  let propString = ''
  inputArguments.forEach(inputArgument => {
    propString += `${ stringify(inputArgument) }_`
  })

  return `${ propString }${ stringify(fn) }`
}
// with weakmaps
export function memoize(fn, ...inputArguments){
  if (arguments.length === 1){
    return (...inputArgumentsHolder) => memoize(fn, ...inputArgumentsHolder)
  }

  const prop = generateProp(fn, ...inputArguments)
  if (prop in cache) return cache[ prop ]

  if (type(fn) === 'Async'){
    return new Promise(resolve => {
      fn(...inputArguments).then(result => {
        cache[ prop ] = result
        resolve(result)
      })
    })
  }

  const result = fn(...inputArguments)
  cache[ prop ] = result

  return result
}
Tests
import { memoize } from './memoize.js'

test('memoize function without input arguments', () => {
  const fn = () => 4
  const memoized = memoize(fn)
  expect(typeof memoized()).toBe('function')
})

test('happy', () => {
  let counter = 0

  const fn = ({ a, b, c }) => {
    counter++

    return a + b - c
  }
  const memoized = memoize(fn)
  expect(memoized({
    a : 1,
    c : 3,
    b : 2,
  })).toBe(0)
  expect(counter).toBe(1)
  expect(memoized({
    c : 3,
    a : 1,
    b : 2,
  })).toBe(0)
  expect(counter).toBe(1)
})

test('normal function', () => {
  let counter = 0
  const fn = (a, b) => {
    counter++

    return a + b
  }
  const memoized = memoize(fn)
  expect(memoized(1, 2)).toBe(3)
  expect(memoized(1, 2)).toBe(3)
  expect(memoized(1, 2)).toBe(3)
  expect(counter).toBe(1)
  expect(memoized(2, 2)).toBe(4)
  expect(counter).toBe(2)
  expect(memoized(1, 2)).toBe(3)
  expect(counter).toBe(2)
})

test('async function', async () => {
  let counter = 0
  const delay = ms =>
    new Promise(resolve => {
      setTimeout(resolve, ms)
    })
  const fn = async (
    ms, a, b
  ) => {
    await delay(ms)
    counter++

    return a + b
  }

  const memoized = memoize(fn)
  await expect(memoized(
    100, 1, 2
  )).resolves.toBe(3)
  await expect(memoized(
    100, 1, 2
  )).resolves.toBe(3)
  await expect(memoized(
    100, 1, 2
  )).resolves.toBe(3)
  expect(counter).toBe(1)
  await expect(memoized(
    100, 2, 2
  )).resolves.toBe(4)
  expect(counter).toBe(2)
  await expect(memoized(
    100, 1, 2
  )).resolves.toBe(3)
  expect(counter).toBe(2)
})

test('string as argument', () => {
  let count = 0
  const foo = 'foo'
  const tester = memoize(n => {
    count++

    return `${ n }bar`
  })
  tester(foo)
  tester(foo)
  tester(foo)

  expect(tester(foo)).toBe('foobar')

  expect(count).toBe(1)

  tester('baz')

  expect(tester('baz')).toBe('bazbar')

  expect(count).toBe(2)
})

---------------

memoizeWith

memoizeWith<T, K extends any[]>(keyGen: any, fn: (...inputs: K) => T): (...inputs: K) => T

Creates a new function that, when invoked, caches the result of calling fn for a given argument set and returns the result.

const keyGen = (a,b) => a + b
let result = 0
const fn = (a,b) =>{
  result++

  return a + b
}
const memoized = R.memoizeWith(keyGen, fn)
memoized(1, 2)
memoized(1, 2)

// => `result` is equal to `1`

Try this R.memoizeWith example in Rambda REPL

All TypeScript definitions
memoizeWith<T, K extends any[]>(keyGen: any, fn: (...inputs: K) => T): (...inputs: K) => T;
R.memoizeWith source
export function memoizeWith(keyGen, fn){
  if (arguments.length === 1){
    return _fn => memoizeWith(keyGen, _fn)
  }
  const cache = new Map()

  return function (){
    const key = keyGen.apply(this, arguments)
    if (!cache.has(key)){
      cache.set(key, fn.apply(this, arguments))
    }

    return cache.get(key)
  }
}
Tests
import { memoizeWith } from './memoizeWith.js'

test('calculates the value for a given input only once', () => {
  let ctr = 0
  const fib = memoizeWith(x => x,
    n => {
      ctr += 1

      return n < 2 ? n : fib(n - 2) + fib(n - 1)
    })
  const result = fib(10)
  expect(result).toBe(55)
  expect(ctr).toBe(11)
})

test('handles multiple parameters', () => {
  const f = memoizeWith((
    a, b, c
  ) => a + b + c,
  (
    a, b, c
  ) => a + ', ' + b + c)

  expect(f(
    'Hello', 'World', '!'
  )).toBe('Hello, World!')
  expect(f(
    'Goodbye', 'Cruel World', '!!!'
  )).toBe('Goodbye, Cruel World!!!')
  expect(f(
    'Hello', 'how are you', '?'
  )).toBe('Hello, how are you?')
  expect(f(
    'Hello', 'World', '!'
  )).toBe('Hello, World!')
})

---------------

merge

merge<A, B>(target: A, newProps: B): A & B
export function merge<Output>(target: any): (newProps: any) => Output

Same as R.mergeRight.

All TypeScript definitions
merge<A, B>(target: A, newProps: B): A & B
merge<Output>(target: any): (newProps: any) => Output;
R.merge source
export { mergeRight as merge } from './mergeRight.js'

---------------

mergeAll

mergeAll<T>(list: object[]): T

It merges all objects of list array sequentially and returns the result.

const list = [
  {a: 1},
  {b: 2},
  {c: 3}
]
const result = R.mergeAll(list)
const expected = {
  a: 1,
  b: 2,
  c: 3
}
// => `result` is equal to `expected`

Try this R.mergeAll example in Rambda REPL

All TypeScript definitions
mergeAll<T>(list: object[]): T;
mergeAll(list: object[]): object;
R.mergeAll source
import { map } from './map.js'
import { mergeRight } from './mergeRight.js'

export function mergeAll(arr){
  let willReturn = {}
  map(val => {
    willReturn = mergeRight(willReturn, val)
  }, arr)

  return willReturn
}
Tests
import { mergeAll } from './mergeAll.js'

test('case 1', () => {
  const arr = [ { a : 1 }, { b : 2 }, { c : 3 } ]
  const expectedResult = {
    a : 1,
    b : 2,
    c : 3,
  }
  expect(mergeAll(arr)).toEqual(expectedResult)
})

test('case 2', () => {
  expect(mergeAll([ { foo : 1 }, { bar : 2 }, { baz : 3 } ])).toEqual({
    foo : 1,
    bar : 2,
    baz : 3,
  })
})

describe('acts as if nil values are simply empty objects', () => {
  it('if the first object is nil', () => {
    expect(mergeAll([ null, { foo : 1 }, { foo : 2 }, { bar : 2 } ])).toEqual({
      foo : 2,
      bar : 2,
    })
  })

  it('if the last object is nil', () => {
    expect(mergeAll([ { foo : 1 }, { foo : 2 }, { bar : 2 }, undefined ])).toEqual({
      foo : 2,
      bar : 2,
    })
  })

  it('if an intermediate object is nil', () => {
    expect(mergeAll([ { foo : 1 }, { foo : 2 }, null, { bar : 2 } ])).toEqual({
      foo : 2,
      bar : 2,
    })
  })
})

---------------

mergeDeepLeft

mergeDeepLeft<Output>(newProps: object, target: object): Output
const result = R.mergeDeepLeft(
  {a: {b: 1}},
  {a: {b: 2, c: 3}}
)
// => {a: {b: 1, c: 3}}

Try this R.mergeDeepLeft example in Rambda REPL

All TypeScript definitions
mergeDeepLeft<Output>(newProps: object, target: object): Output;
mergeDeepLeft<Output>(newProps: object): (target: object) => Output;

// RAMBDAX_MARKER_START
R.mergeDeepLeft source
import { mergeDeepRight } from './mergeDeepRight.js';

export function mergeDeepLeft(newProps, target) {
	return mergeDeepRight(target, newProps);
}
Tests
import { mergeDeepLeft } from './mergeDeepLeft';

it('takes two objects, recursively merges their own properties and returns a new object', () => {
	const a = { w: 1, x: 2, y: { z: 3 } };
	const b = { a: 4, b: 5, c: { d: 6 } };
	expect(mergeDeepLeft(a, b)).toEqual({
		w: 1,
		x: 2,
		y: { z: 3 },
		a: 4,
		b: 5,
		c: { d: 6 },
	});
});

it('overrides properties in the second object with properties in the first object', () => {
	const a = { a: { b: 1, c: 2 }, y: 0 };
	const b = { a: { b: 3, d: 4 }, z: 0 };
	expect(mergeDeepLeft(a, b)).toEqual({ a: { b: 1, c: 2, d: 4 }, y: 0, z: 0 });
});

it('is not destructive', () => {
	const a = { w: 1, x: { y: 2 } };
	const res = mergeDeepLeft(a, { x: { y: 3 } });
	expect(a).not.toBe(res);
	expect(a.x).not.toBe(res.x);
	expect(res).toEqual({ w: 1, x: { y: 2 } });
});

it('reports only own properties', () => {
	const a = { w: 1, x: { y: 2 } };
	function Cla() {}
	Cla.prototype.y = 5;
	expect(mergeDeepLeft({ x: new Cla() }, a)).toEqual({ w: 1, x: { y: 2 } });
	expect(mergeDeepLeft(a, { x: new Cla() })).toEqual({ w: 1, x: { y: 2 } });
});

---------------

mergeDeepRight

mergeDeepRight<Output>(target: object, newProps: object): Output

Creates a new object with the own properties of the first object merged with the own properties of the second object. If a key exists in both objects:

  • and both values are objects, the two values will be recursively merged
  • otherwise the value from the second object will be used.
All TypeScript definitions
mergeDeepRight<Output>(target: object, newProps: object): Output;
mergeDeepRight<Output>(target: object): (newProps: object) => Output;
R.mergeDeepRight source
import { clone } from './clone.js'
import { type } from './type.js'

export function mergeDeepRight(target, source){
  if (arguments.length === 1){
    return sourceHolder => mergeDeepRight(target, sourceHolder)
  }

  const willReturn = clone(target)

  Object.keys(source).forEach(key => {
    if (type(source[ key ]) === 'Object'){
      if (type(target[ key ]) === 'Object'){
        willReturn[ key ] = mergeDeepRight(target[ key ], source[ key ])
      } else {
        willReturn[ key ] = source[ key ]
      }
    } else {
      willReturn[ key ] = source[ key ]
    }
  })

  return willReturn
}
Tests
import { mergeDeepRight } from './mergeDeepRight.js'

const student = {
  name    : 'foo',
  age     : 10,
  contact : {
    a     : 1,
    email : 'foo@example.com',
  },
}
const teacher = {
  age     : 40,
  contact : { email : 'baz@example.com' },
  songs   : { title : 'Remains the same' },
}

test('when merging object with lists inside them', () => {
  const a = {
    a : [ 1, 2, 3 ],
    b : [ 4, 5, 6 ],
  }
  const b = {
    a : [ 7, 8, 9 ],
    b : [ 10, 11, 12 ],
  }
  const result = mergeDeepRight(a, b)
  const expected = {
    a : [ 7, 8, 9 ],
    b : [ 10, 11, 12 ],
  }
  expect(result).toEqual(expected)
})

test('happy', () => {
  const result = mergeDeepRight(student, teacher)
  const curryResult = mergeDeepRight(student)(teacher)
  const expected = {
    age     : 40,
    name    : 'foo',
    contact : {
      a     : 1,
      email : 'baz@example.com',
    },
    songs : { title : 'Remains the same' },
  }

  expect(result).toEqual(expected)
  expect(curryResult).toEqual(expected)
})

test('issue 650', () => {
  expect(Object.keys(mergeDeepRight({ a : () => {} }, { b : () => {} }))).toEqual([
    'a',
    'b',
  ])
})

test('ramda compatible test 1', () => {
  const a = {
    w : 1,
    x : 2,
    y : { z : 3 },
  }
  const b = {
    a : 4,
    b : 5,
    c : { d : 6 },
  }
  const result = mergeDeepRight(a, b)
  const expected = {
    w : 1,
    x : 2,
    y : { z : 3 },
    a : 4,
    b : 5,
    c : { d : 6 },
  }

  expect(result).toEqual(expected)
})

test('ramda compatible test 2', () => {
  const a = {
    a : {
      b : 1,
      c : 2,
    },
    y : 0,
  }
  const b = {
    a : {
      b : 3,
      d : 4,
    },
    z : 0,
  }
  const result = mergeDeepRight(a, b)
  const expected = {
    a : {
      b : 3,
      c : 2,
      d : 4,
    },
    y : 0,
    z : 0,
  }

  expect(result).toEqual(expected)
})

test('ramda compatible test 3', () => {
  const a = {
    w : 1,
    x : { y : 2 },
  }
  const result = mergeDeepRight(a, { x : { y : 3 } })
  const expected = {
    w : 1,
    x : { y : 3 },
  }
  expect(result).toEqual(expected)
})

test('functions are not discarded', () => {
  const obj = { foo : () => {} }
  expect(typeof mergeDeepRight(obj, {}).foo).toBe('function')
})

---------------

mergeLeft

mergeLeft<Output>(newProps: object, target: object): Output

Same as R.merge, but in opposite direction.

const result = R.mergeLeft(
  {a: 10},
  {a: 1, b: 2}
)
// => {a:10, b: 2}

Try this R.mergeLeft example in Rambda REPL

All TypeScript definitions
mergeLeft<Output>(newProps: object, target: object): Output;
mergeLeft<Output>(newProps: object): (target: object) => Output;
R.mergeLeft source
import { mergeRight } from './mergeRight.js'

export function mergeLeft(x, y){
  if (arguments.length === 1) return _y => mergeLeft(x, _y)

  return mergeRight(y, x)
}
Tests
import { mergeLeft } from './mergeLeft.js'

const obj = {
  foo : 1,
  bar : 2,
}

test('happy', () => {
  expect(mergeLeft({ bar : 20 }, obj)).toEqual({
    foo : 1,
    bar : 20,
  })
})

test('curry', () => {
  expect(mergeLeft({ baz : 3 })(obj)).toEqual({
    foo : 1,
    bar : 2,
    baz : 3,
  })
})

test('when undefined or null instead of object', () => {
  expect(mergeLeft(null, undefined)).toEqual({})
  expect(mergeLeft(obj, null)).toEqual(obj)
  expect(mergeLeft(obj, undefined)).toEqual(obj)
  expect(mergeLeft(undefined, obj)).toEqual(obj)
})

---------------

mergeRight

mergeRight<A, B>(target: A, newProps: B): A & B
export function mergeRight<Output>(target: any): (newProps: any) => Output

It creates a copy of target object with overwritten newProps properties. Previously known as R.merge but renamed after Ramda did the same.

const target = { 'foo': 0, 'bar': 1 }
const newProps = { 'foo': 7 }

const result = R.mergeRight(target, newProps)
// => { 'foo': 7, 'bar': 1 }

Try this R.mergeRight example in Rambda REPL

All TypeScript definitions
mergeRight<A, B>(target: A, newProps: B): A & B
mergeRight<Output>(target: any): (newProps: any) => Output;
R.mergeRight source
export function mergeRight(target, newProps){
  if (arguments.length === 1)
    return _newProps => mergeRight(target, _newProps)

  return Object.assign(
    {}, target || {}, newProps || {}
  )
}
Tests
import { mergeRight } from './mergeRight.js'

const obj = {
  foo : 1,
  bar : 2,
}

test('happy', () => {
  expect(mergeRight(obj, { bar : 20 })).toEqual({
    foo : 1,
    bar : 20,
  })
})

test('curry', () => {
  expect(mergeRight(obj)({ baz : 3 })).toEqual({
    foo : 1,
    bar : 2,
    baz : 3,
  })
})

/**
 * https://github.com/selfrefactor/rambda/issues/77
 */
test('when undefined or null instead of object', () => {
  expect(mergeRight(null, undefined)).toEqual({})
  expect(mergeRight(obj, null)).toEqual(obj)
  expect(mergeRight(obj, undefined)).toEqual(obj)
  expect(mergeRight(undefined, obj)).toEqual(obj)
})

test('with function inside object', () => {
  const result = mergeRight({ a : 1 }, { b : () => 1 })
  expect(typeof result.b).toBe('function')
})

describe('acts as if nil values are simply empty objects', () => {
  const a = {
    w : 1,
    x : 2,
  }
  const b = {
    w : 100,
    y : 3,
    z : 4,
  }

  it('if the first object is nil', () => {
    expect(mergeRight(null, b)).toEqual(b)
  })

  it('if the second object is nil', () => {
    expect(mergeRight(a, undefined)).toEqual(a)
  })

  it('if both objects are nil', () => {
    expect(mergeRight(null, undefined)).toEqual({})
  })
})

---------------

mergeWith

mergeWith(fn: (x: any, z: any) => any, a: Record<string, unknown>, b: Record<string, unknown>): Record<string, unknown>

It takes two objects and a function, which will be used when there is an overlap between the keys.

const result = R.mergeWith(
  R.concat,
  {values : [ 10, 20 ]},
  {values : [ 15, 35 ]}
)
// => [ 10, 20, 15, 35 ]

Try this R.mergeWith example in Rambda REPL

All TypeScript definitions
mergeWith(fn: (x: any, z: any) => any, a: Record<string, unknown>, b: Record<string, unknown>): Record<string, unknown>;
mergeWith<Output>(fn: (x: any, z: any) => any, a: Record<string, unknown>, b: Record<string, unknown>): Output;
mergeWith(fn: (x: any, z: any) => any, a: Record<string, unknown>): (b: Record<string, unknown>) => Record<string, unknown>;
mergeWith<Output>(fn: (x: any, z: any) => any, a: Record<string, unknown>): (b: Record<string, unknown>) => Output;
mergeWith(fn: (x: any, z: any) => any): <U, V>(a: U, b: V) => Record<string, unknown>;
mergeWith<Output>(fn: (x: any, z: any) => any): <U, V>(a: U, b: V) => Output;
R.mergeWith source
import { curry } from './curry.js'

export function mergeWithFn(
  mergeFn, aInput, bInput
){
  const a = aInput ?? {}
  const b = bInput ?? {}
  const willReturn = {}

  Object.keys(a).forEach(key => {
    if (b[ key ] === undefined) willReturn[ key ] = a[ key ]
    else willReturn[ key ] = mergeFn(a[ key ], b[ key ])
  })

  Object.keys(b).forEach(key => {
    if (willReturn[ key ] !== undefined) return

    if (a[ key ] === undefined) willReturn[ key ] = b[ key ]
    else willReturn[ key ] = mergeFn(a[ key ], b[ key ])
  })

  return willReturn
}

export const mergeWith = curry(mergeWithFn)
Tests
import { concat } from './concat.js'
import { mergeWithFn } from './mergeWith.js'

test('happy', () => {
  const result = mergeWithFn(
    concat,
    {
      a      : true,
      values : [ 10, 20 ],
    },
    {
      b      : true,
      values : [ 15, 35 ],
    }
  )
  const expected = {
    a      : true,
    b      : true,
    values : [ 10, 20, 15, 35 ],
  }
  expect(result).toEqual(expected)
})

// https://github.com/ramda/ramda/pull/3222/files#diff-d925d9188b478d2f1d4b26012c6dddac374f9e9d7a336604d654b9a113bfc857
describe('acts as if nil values are simply empty objects', () => {
  it('if the first object is nil and the second empty', () => {
    expect(mergeWithFn(
      concat, undefined, {}
    )).toEqual({})
  })

  it('if the first object is empty and the second nil', () => {
    expect(mergeWithFn(
      concat, {}, null
    )).toEqual({})
  })

  it('if both objects are nil', () => {
    expect(mergeWithFn(
      concat, undefined, null
    )).toEqual({})
  })

  it('if the first object is not empty and the second is nil', () => {
    expect(mergeWithFn(
      concat, { a : 'a' }, null
    )).toEqual({ a : 'a' })
  })

  it('if the first object is nil and the second is not empty', () => {
    expect(mergeWithFn(
      concat, undefined, { a : 'a' }
    )).toEqual({ a : 'a' })
  })
})

---------------

min

min<T extends Ord>(x: T, y: T): T

It returns the lesser value between x and y.

const result = [
  R.min(5, 7),  
  R.min('bar', 'foo'),  
]
// => [5, 'bar']

Try this R.min example in Rambda REPL

All TypeScript definitions
min<T extends Ord>(x: T, y: T): T;
min<T extends Ord>(x: T): (y: T) => T;
R.min source
export function min(x, y){
  if (arguments.length === 1) return _y => min(x, _y)

  return y < x ? y : x
}
Tests
import { min } from './min.js'

test('happy', () => {
  expect(min(2, 1)).toBe(1)
  expect(min(1)(2)).toBe(1)
})

---------------

minBy

minBy<T>(compareFn: (input: T) => Ord, x: T, y: T): T

It returns the lesser value between x and y according to compareFn function.

const compareFn = Math.abs

R.minBy(compareFn, -5, 2) // => -5

Try this R.minBy example in Rambda REPL

All TypeScript definitions
minBy<T>(compareFn: (input: T) => Ord, x: T, y: T): T;
minBy<T>(compareFn: (input: T) => Ord, x: T): (y: T) => T;
minBy<T>(compareFn: (input: T) => Ord): (x: T) => (y: T) => T;
R.minBy source
import { curry } from './curry.js'

export function minByFn(
  compareFn, x, y
){
  return compareFn(y) < compareFn(x) ? y : x
}

export const minBy = curry(minByFn)
Tests
import { minBy } from './minBy.js'

test('happy', () => {
  expect(minBy(
    Math.abs, -5, 2
  )).toBe(2)
})

test('curried', () => {
  expect(minBy(Math.abs)(2, -5)).toBe(2)
  expect(minBy(Math.abs)(2)(-5)).toBe(2)
})

---------------

modify

modify<K extends PropertyKey, T>(prop: K, fn: (value: T) => T): <U extends Record<K, T>>(object: U) => U
const result = R.modify()
// =>

Try this R.modify example in Rambda REPL

All TypeScript definitions
modify<K extends PropertyKey, T>(prop: K, fn: (value: T) => T): <U extends Record<K, T>>(object: U) => U;
modify<U, K extends keyof U>(prop: K, fn: (value: U[K]) => U[K], object: U): U;
modify<K extends PropertyKey>(prop: K): {
  <T>(fn: (value: T) => T): <U extends Record<K, T>>(object: U) => U;
  <T, U extends Record<K, T>>(fn: (value: T) => T, object: U): U;
};
R.modify source
import { isArray } from './_internals/isArray.js'
import { isIterable } from './_internals/isIterable.js'
import { curry } from './curry.js'
import { updateFn } from './update.js'

function modifyFn(
  property, fn, iterable
){
  if (!isIterable(iterable)) return iterable
  if (iterable[ property ] === undefined) return iterable
  if (isArray(iterable)){
    return updateFn(
      property, fn(iterable[ property ]), iterable
    )
  }

  return {
    ...iterable,
    [ property ] : fn(iterable[ property ]),
  }
}

export const modify = curry(modifyFn)
Tests
import { modify as modifyRamda } from 'ramda'

import { compareCombinations, FALSY_VALUES } from './_internals/testUtils.js'
import { add } from './add.js'
import { compose } from './compose.js'
import { modify } from './modify.js'

const person = {
  name : 'foo',
  age  : 20,
}

test('happy', () => {
  expect(modify(
    'age', x => x + 1, person
  )).toEqual({
    name : 'foo',
    age  : 21,
  })
})

test('property is missing', () => {
  expect(modify(
    'foo', x => x + 1, person
  )).toEqual(person)
})

test('adjust if `array` at the given key with the `transformation` function', () => {
  expect(modify(
    1, add(1), [ 100, 1400 ]
  )).toEqual([ 100, 1401 ])
})

describe('ignores transformations if the input value is not Array and Object', () => {
  ;[ 42, undefined, null, '' ].forEach(value => {
    it(`${ value }`, () => {
      expect(modify(
        'a', add(1), value
      )).toEqual(value)
    })
  })
})

const possibleProperties = [ ...FALSY_VALUES, 'foo', 0 ]
const possibleTransformers = [
  ...FALSY_VALUES,
  add(1),
  add('foo'),
  compose,
  String,
]
const possibleObjects = [
  ...FALSY_VALUES,
  {},
  [ 1, 2, 3 ],
  {
    a   : 1,
    foo : 2,
  },
  {
    a   : 1,
    foo : [ 1 ],
  },
  {
    a   : 1,
    foo : 'bar',
  },
]

describe('brute force', () => {
  compareCombinations({
    fn          : modify,
    fnRamda     : modifyRamda,
    firstInput  : possibleProperties,
    secondInput : possibleTransformers,
    thirdInput  : possibleObjects,
    callback    : errorsCounters => {
      expect(errorsCounters).toMatchInlineSnapshot(`
        {
          "ERRORS_MESSAGE_MISMATCH": 0,
          "ERRORS_TYPE_MISMATCH": 0,
          "RESULTS_MISMATCH": 0,
          "SHOULD_NOT_THROW": 0,
          "SHOULD_THROW": 0,
          "TOTAL_TESTS": 630,
        }
      `)
    },
  })
})

---------------

modifyPath

modifyPath<T extends Record<string, unknown>>(path: Path, fn: (x: any) => unknown, object: Record<string, unknown>): T

It changes a property of object on the base of provided path and transformer function.

const result = R.modifyPath('a.b.c', x=> x+1, {a:{b: {c:1}}})
// => {a:{b: {c:2}}}

Try this R.modifyPath example in Rambda REPL

All TypeScript definitions
modifyPath<T extends Record<string, unknown>>(path: Path, fn: (x: any) => unknown, object: Record<string, unknown>): T;
modifyPath<T extends Record<string, unknown>>(path: Path, fn: (x: any) => unknown): (object: Record<string, unknown>) => T;
modifyPath<T extends Record<string, unknown>>(path: Path): (fn: (x: any) => unknown) => (object: Record<string, unknown>) => T;
R.modifyPath source
import { createPath } from './_internals/createPath.js'
import { isArray } from './_internals/isArray.js'
import { assoc } from './assoc.js'
import { curry } from './curry.js'
import { path as pathModule } from './path.js'

export function modifyPathFn(
  pathInput, fn, object
){
  const path = createPath(pathInput)
  if (path.length === 1){
    return {
      ...object,
      [ path[ 0 ] ] : fn(object[ path[ 0 ] ]),
    }
  }
  if (pathModule(path, object) === undefined) return object

  const val = modifyPath(
    Array.prototype.slice.call(path, 1),
    fn,
    object[ path[ 0 ] ]
  )
  if (val === object[ path[ 0 ] ]){
    return object
  }

  return assoc(
    path[ 0 ], val, object
  )
}

export const modifyPath = curry(modifyPathFn)
Tests
import { modifyPath } from './modifyPath.js'

test('happy', () => {
  const result = modifyPath(
    'a.b.c', x => x + 1, { a : { b : { c : 1 } } }
  )
  expect(result).toEqual({ a : { b : { c : 2 } } })
})

test('with array', () => {
  const input = { foo : [ { bar : '123' } ] }
  const result = modifyPath(
    'foo.0.bar', x => x + 'foo', input
  )
  expect(result).toEqual({ foo : { 0 : { bar : '123foo' } } })
})

---------------

modulo

modulo(x: number, y: number): number

Curried version of x%y.

R.modulo(17, 3) // => 2

Try this R.modulo example in Rambda REPL

All TypeScript definitions
modulo(x: number, y: number): number;
modulo(x: number): (y: number) => number;
R.modulo source
export function modulo(x, y){
  if (arguments.length === 1) return _y => modulo(x, _y)

  return x % y
}
Tests
import { modulo } from './modulo.js'

test('happy', () => {
  expect(modulo(17, 3)).toBe(2)
  expect(modulo(15)(6)).toBe(3)
})

---------------

move

move<T>(fromIndex: number, toIndex: number, list: T[]): T[]

It returns a copy of list with exchanged fromIndex and toIndex elements.

💥 Rambda.move doesn't support negative indexes - it throws an error.

const list = [1, 2, 3]
const result = R.move(0, 1, list)
// => [2, 1, 3]

Try this R.move example in Rambda REPL

All TypeScript definitions
move<T>(fromIndex: number, toIndex: number, list: T[]): T[];
move(fromIndex: number, toIndex: number): <T>(list: T[]) => T[];
move(fromIndex: number): {
    <T>(toIndex: number, list: T[]): T[];
    (toIndex: number): <T>(list: T[]) => T[];
};
R.move source
import { cloneList } from './_internals/cloneList.js'
import { curry } from './curry.js'

function moveFn(
  fromIndex, toIndex, list
){
  if (fromIndex < 0 || toIndex < 0){
    throw new Error('Rambda.move does not support negative indexes')
  }
  if (fromIndex > list.length - 1 || toIndex > list.length - 1) return list

  const clone = cloneList(list)
  clone[ fromIndex ] = list[ toIndex ]
  clone[ toIndex ] = list[ fromIndex ]

  return clone
}

export const move = curry(moveFn)
Tests
import { move } from './move.js'
const list = [ 1, 2, 3, 4 ]

test('happy', () => {
  const result = move(
    0, 1, list
  )

  expect(result).toEqual([ 2, 1, 3, 4 ])
})

test('with negative index', () => {
  const errorMessage = 'Rambda.move does not support negative indexes'
  expect(() => move(
    0, -1, list
  )).toThrowErrorMatchingInlineSnapshot('"Rambda.move does not support negative indexes"')
  expect(() => move(
    -1, 0, list
  )).toThrowErrorMatchingInlineSnapshot('"Rambda.move does not support negative indexes"')
})

test('when indexes are outside the list outbounds', () => {
  const result1 = move(
    10, 1, list
  )
  const result2 = move(
    1, 10, list
  )

  expect(result1).toEqual(list)
  expect(result2).toEqual(list)
})

---------------

multiply

multiply(x: number, y: number): number

Curried version of x*y.

R.multiply(2, 4) // => 8

Try this R.multiply example in Rambda REPL

All TypeScript definitions
multiply(x: number, y: number): number;
multiply(x: number): (y: number) => number;
R.multiply source
export function multiply(x, y){
  if (arguments.length === 1) return _y => multiply(x, _y)

  return x * y
}
Tests
import { multiply } from './multiply.js'

test('happy', () => {
  expect(multiply(2, 4)).toBe(8)
  expect(multiply(2)(4)).toBe(8)
})

---------------

negate

negate(x: number): number
R.negate(420)// => -420

Try this R.negate example in Rambda REPL

All TypeScript definitions
negate(x: number): number;
R.negate source
export function negate(x){
  return -x
}
Tests
import { negate } from './negate.js'

test('negate', () => {
  expect(negate(420)).toBe(-420)
  expect(negate(-13)).toBe(13)
})

---------------

nextIndex

nextIndex(index: number, list: any[]): number

It returns the next index of the list.

If we have reached the end of the list, then it will return 0.

const list = [1, 2, 3]

const result = [
  R.nextIndex(0, list),
  R.nextIndex(1, list),
  R.nextIndex(2, list),
  R.nextIndex(10, list)
]
// => [1, 2, 0, 0]

Try this R.nextIndex example in Rambda REPL

All TypeScript definitions
nextIndex(index: number, list: any[]): number;
R.nextIndex source
export function nextIndex(index, list){
  return index >= list.length - 1 ? 0 : index + 1
}
Tests
import { nextIndex } from './nextIndex.js'

const list = [ 1, 2, 3, 4 ]

test('happy path', () => {
  expect(nextIndex(2, list)).toBe(3)
})

test('go back to the start', () => {
  expect(nextIndex(3, list)).toBe(0)
})

test('current index is too big', () => {
  expect(nextIndex(32, list)).toBe(0)
})

---------------

none

none<T>(predicate: (x: T) => boolean, list: T[]): boolean

It returns true, if all members of array list returns false, when applied as argument to predicate function.

const list = [ 0, 1, 2, 3, 4 ]
const predicate = x => x > 6

const result = R.none(predicate, arr)
// => true

Try this R.none example in Rambda REPL

All TypeScript definitions
none<T>(predicate: (x: T) => boolean, list: T[]): boolean;
none<T>(predicate: (x: T) => boolean): (list: T[]) => boolean;
R.none source
export function none(predicate, list){
  if (arguments.length === 1) return _list => none(predicate, _list)

  for (let i = 0; i < list.length; i++){
    if (predicate(list[ i ])) return false
  }

  return true
}
Tests
import { none } from './none.js'

const isEven = n => n % 2 === 0

test('when true', () => {
  expect(none(isEven, [ 1, 3, 5, 7 ])).toBeTrue()
})

test('when false curried', () => {
  expect(none(input => input > 1, [ 1, 2, 3 ])).toBeFalse()
})

---------------

noop

noop(): void
All TypeScript definitions
noop(): void;

// RAMBDAX_MARKER_END
// ============================================

export as namespace R
R.noop source
export function noop(){}

---------------

not

not(input: any): boolean

It returns a boolean negated version of input.

R.not(false) // true

Try this R.not example in Rambda REPL

All TypeScript definitions
not(input: any): boolean;
R.not source
export function not(input){
  return !input
}
Tests
import { not } from './not.js'

test('not', () => {
  expect(not(false)).toBeTrue()
  expect(not(true)).toBeFalse()
  expect(not(0)).toBeTrue()
  expect(not(1)).toBeFalse()
})

---------------

nth

nth(index: number, input: string): string

Curried version of input[index].

const list = [1, 2, 3]
const str = 'foo'

const result = [
  R.nth(2, list),
  R.nth(6, list),
  R.nth(0, str),
]
// => [3, undefined, 'f']

Try this R.nth example in Rambda REPL

All TypeScript definitions
nth(index: number, input: string): string;	
nth<T>(index: number, input: T[]): T | undefined;	
nth(n: number): {
  <T>(input: T[]): T | undefined;
  (input: string): string;
};
R.nth source
export function nth(index, input){
  if (arguments.length === 1) return _input => nth(index, _input)

  const idx = index < 0 ? input.length + index : index

  return Object.prototype.toString.call(input) === '[object String]' ?
    input.charAt(idx) :
    input[ idx ]
}
Tests
import { nth } from './nth.js'

test('happy', () => {
  expect(nth(2, [ 1, 2, 3, 4 ])).toBe(3)
})

test('with curry', () => {
  expect(nth(2)([ 1, 2, 3, 4 ])).toBe(3)
})

test('with string and correct index', () => {
  expect(nth(2)('foo')).toBe('o')
})

test('with string and invalid index', () => {
  expect(nth(20)('foo')).toBe('')
})

test('with negative index', () => {
  expect(nth(-3)([ 1, 2, 3, 4 ])).toBe(2)
})

---------------

objOf

objOf<T, K extends string>(key: K, value: T): Record<K, T>

It creates an object with a single key-value pair.

const result = R.objOf('foo', 'bar')
// => {foo: 'bar'}

Try this R.objOf example in Rambda REPL

All TypeScript definitions
objOf<T, K extends string>(key: K, value: T): Record<K, T>;
objOf<K extends string>(key: K): <T>(value: T) => Record<K, T>;
R.objOf source
export function objOf(key, value){
  if (arguments.length === 1){
    return _value => objOf(key, _value)
  }

  return { [ key ] : value }
}
Tests
import { objOf as objOfRamda } from 'ramda'

import { compareCombinations } from './_internals/testUtils.js'
import { objOf } from './objOf.js'

test('happy', () => {
  expect(objOf('foo', 42)).toEqual({ foo : 42 })
})

test('with bad inputs', () => {
  expect(objOf(null, undefined)).toEqual({ null : undefined })
})

test('curried', () => {
  expect(objOf('foo')(42)).toEqual({ foo : 42 })
})

describe('brute force', () => {
  const possibleInputs = [ 0, 1, null, undefined, [], {} ]

  compareCombinations({
    firstInput  : possibleInputs,
    secondInput : possibleInputs,
    callback    : errorsCounters => {
      expect(errorsCounters).toMatchInlineSnapshot(`
        {
          "ERRORS_MESSAGE_MISMATCH": 0,
          "ERRORS_TYPE_MISMATCH": 0,
          "RESULTS_MISMATCH": 0,
          "SHOULD_NOT_THROW": 0,
          "SHOULD_THROW": 0,
          "TOTAL_TESTS": 36,
        }
      `)
    },
    fn      : objOf,
    fnRamda : objOfRamda,
  })
})

---------------

of

of<T>(x: T): T[]
R.of(null); // => [null]
R.of([42]); // => [[42]]

Try this R.of example in Rambda REPL

All TypeScript definitions
of<T>(x: T): T[];
R.of source
export function of(value){
  return [ value ]
}
Tests
import { of } from './of.js'

test('happy', () => {
  expect(of(3)).toEqual([ 3 ])

  expect(of(null)).toEqual([ null ])
})

---------------

ok

ok(...inputs: any[]): (...schemas: any[]) => void | never

It checks if inputs are following schemas specifications according to R.isValid.

If validation fails, it throws.

💥 It is same as R.pass but instead of returning false, it throws an error.

const result = R.ok(
  1,
  ['foo', 'bar']
)(
  Number,
  [String]
)
// => undefined

Try this R.ok example in Rambda REPL

All TypeScript definitions
ok(...inputs: any[]): (...schemas: any[]) => void | never;
R.ok source
import { any } from './any.js'
import { glue } from './glue.js'
import { fromPrototypeToString, isValid } from './isValid.js'
import { map } from './map.js'
import { type } from './type.js'

export function schemaToString(schema){
  if (type(schema) !== 'Object'){
    return fromPrototypeToString(schema).rule
  }

  return map(x => {
    const { rule, parsed } = fromPrototypeToString(x)
    const xType = type(x)

    if (xType === 'Function' && !parsed) return 'Function'

    return parsed ? rule : xType
  }, schema)
}

export function check(singleInput, schema){
  return isValid({
    input  : { singleInput },
    schema : { singleInput : schema },
  })
}

export function ok(...inputs){
  return (...schemas) => {
    let failedSchema

    const anyError = any((singleInput, i) => {
      const schema = schemas[ i ] === undefined ? schemas[ 0 ] : schemas[ i ]

      const checked = check(singleInput, schema)
      if (!checked){
        failedSchema = JSON.stringify({
          input  : singleInput,
          schema : schemaToString(schema),
        })
      }

      return !checked
    }, inputs)

    if (anyError){
      const errorMessage =
        inputs.length > 1 ?
          glue(`
        Failed R.ok -
        reason: ${ failedSchema }
        all inputs: ${ JSON.stringify(inputs) }
        all schemas: ${ JSON.stringify(schemas.map(schemaToString)) }
      `,
          '\n') :
          `Failed R.ok - ${ failedSchema }`

      throw new Error(errorMessage)
    }
  }
}
Tests
import { ok, schemaToString } from './ok.js'

test('happy', () => {
  expect(() => {
    ok(
      1, 'foo', {}
    )(
      'number', 'string', 'object'
    )
  }).not.toThrow()
})

test('when validation fails', () => {
  expect(() => ok(
    1, 'foo', {}
  )(
    'number', 'string', 'string'
  ))
    .toThrowErrorMatchingInlineSnapshot(`
    "Failed R.ok -
    reason: {"input":{},"schema":"string"}
    all inputs: [1,"foo",{}]
    all schemas: ["number","string","string"]"
  `)
})

test('schema in error message', () => {
  const result = schemaToString({
    _a : [ Number ],
    a  : Number,
    b  : x => x > 2,
    c  : [ 'foo', 'bar' ],
    d  : [ { a : String } ],
    e  : 'boolean',
    f  : Array,
    h  : Object,
  })

  expect(result).toMatchInlineSnapshot(`
    {
      "_a": "Array",
      "a": "number",
      "b": "Function",
      "c": "Array",
      "d": "Array",
      "e": "String",
      "f": "array",
      "h": "object",
    }
  `)
})

test('error contains schema', () => {
  try {
    ok(
      1, 'foo', {}
    )(
      { a : Number }, String, String
    )
    expect(false).toBeTrue()
  } catch (e){
    expect(e.message.startsWith('Failed R.ok -')).toBeTruthy()
    expect(e).toBeInstanceOf(Error)
  }
})

test('when not throws with single schema', () => {
  expect(() => ok(
    1, 2, 3
  )('number')).not.toThrow()
})

test('when throws with single schema', () => {
  expect(() => ok(
    1, 2, '3'
  )('number')).toThrowErrorMatchingInlineSnapshot(`
    "Failed R.ok -
    reason: {"input":"3","schema":"number"}
    all inputs: [1,2,"3"]
    all schemas: ["number"]"
  `)
})

test('when throws with single input', () => {
  expect(() => ok('3')('number')).toThrowErrorMatchingInlineSnapshot('"Failed R.ok - {"input":"3","schema":"number"}"')
})

---------------

omit

omit<T, K extends string>(propsToOmit: K[], obj: T): Omit<T, K>

It returns a partial copy of an obj without propsToOmit properties.

💥 When using this method with TypeScript, it is much easier to pass propsToOmit as an array. If passing a string, you will need to explicitly declare the output type.

const obj = {a: 1, b: 2, c: 3}
const propsToOmit = 'a,c,d'
const propsToOmitList = ['a', 'c', 'd']

const result = [
  R.omit(propsToOmit, Record<string, unknown>), 
  R.omit(propsToOmitList, Record<string, unknown>) 
]
// => [{b: 2}, {b: 2}]

Try this R.omit example in Rambda REPL

All TypeScript definitions
omit<T, K extends string>(propsToOmit: K[], obj: T): Omit<T, K>;
omit<K extends string>(propsToOmit: K[]): <T>(obj: T) => Omit<T, K>;
omit<T, U>(propsToOmit: string, obj: T): U;
omit<T, U>(propsToOmit: string): (obj: T) => U;
omit<T>(propsToOmit: string, obj: object): T;
omit<T>(propsToOmit: string): (obj: object) => T;
R.omit source
import { createPath } from './_internals/createPath.js'
import { includes } from './_internals/includes.js'

export function omit(propsToOmit, obj){
  if (arguments.length === 1) return _obj => omit(propsToOmit, _obj)

  if (obj === null || obj === undefined)
    return undefined

  const propsToOmitValue = createPath(propsToOmit, ',')
  const willReturn = {}

  for (const key in obj)
    if (!includes(key, propsToOmitValue))
      willReturn[ key ] = obj[ key ]

  return willReturn
}
Tests
import { omit } from './omit.js'

test('with string as condition', () => {
  const obj = {
    a : 1,
    b : 2,
    c : 3,
  }
  const result = omit('a,c', obj)
  const resultCurry = omit('a,c')(obj)
  const expectedResult = { b : 2 }

  expect(result).toEqual(expectedResult)
  expect(resultCurry).toEqual(expectedResult)
})

test.only('with number as property to omit', () => {
  const obj = {
    1 : 1,
    b : 2,
  }
  const result = omit([ 1 ], obj)
  expect(result).toEqual({ b : 2 })
})

test('with null', () => {
  expect(omit('a,b', null)).toBeUndefined()
})

test('happy', () => {
  expect(omit([ 'a', 'c' ])({
    a : 'foo',
    b : 'bar',
    c : 'baz',
  })).toEqual({ b : 'bar' })
})

---------------

on

on<T, U, R>(binaryFn: (a: U, b: U) => R, unaryFn: (value: T) => U, a: T, b: T): R

It passes the two inputs through unaryFn and then the results are passed as inputs the the binaryFn to receive the final result(binaryFn(unaryFn(FIRST_INPUT), unaryFn(SECOND_INPUT))).

This method is also known as P combinator.

const result = R.on((a, b) => a + b, R.prop('a'), {b:0, a:1}, {a:2})
// => 3

Try this R.on example in Rambda REPL

All TypeScript definitions
on<T, U, R>(binaryFn: (a: U, b: U) => R, unaryFn: (value: T) => U, a: T, b: T): R;
on<T, U, R>(binaryFn: (a: U, b: U) => R, unaryFn: (value: T) => U, a: T): (b: T) => R;
on<T, U, R>(binaryFn: (a: U, b: U) => R, unaryFn: (value: T) => U): {
    (a: T, b: T): R;
    (a: T): (b: T) => R;
};
R.on source
export function on(
  binaryFn, unaryFn, a, b
){
  if (arguments.length === 3){
    return _b => on(
      binaryFn, unaryFn, a, _b
    )
  }
  if (arguments.length === 2){
    return (_a, _b) => on(
      binaryFn, unaryFn, _a, _b
    )
  }

  return binaryFn(unaryFn(a), unaryFn(b))
}
Tests
import { on } from './on.js'

const binaryFn = (a, b) => a === b
const unaryFn = x => x.a
const a = {
  b : 0,
  a : 1,
}
const b = { a : 1 }

test('happy', () => {
  expect(on(
    binaryFn, unaryFn, a, b
  )).toBeTrue()
})

test('return type is not limited to boolean', () => {
  expect(on(
    binaryFn, unaryFn, a, b
  )).toBeTrue()
})

test('curried - last input', () => {
  expect(on(
    binaryFn, unaryFn, a
  )(b)).toBeTrue()
})

test('curried - last two inputs', () => {
  expect(on(binaryFn, unaryFn)(a, b)).toBeTrue()
})

test('not supported curried case', () => {
  expect(() =>
    on(binaryFn, unaryFn)(a)(b)).toThrowErrorMatchingInlineSnapshot('"Cannot read properties of undefined (reading \'a\')"')
})

---------------

once

once<T extends AnyFunction, C = unknown>(fn: T, context?: C): T

It returns a function, which invokes only once fn function.

let result = 0
const addOnce = R.once((x) => result = result + x)

addOnce(1)
addOnce(1)
// => 1

Try this R.once example in Rambda REPL

All TypeScript definitions
once<T extends AnyFunction, C = unknown>(fn: T, context?: C): T;
R.once source
import { curry } from './curry.js'

function onceFn(fn, context){
  let result

  return function (){
    if (fn){
      result = fn.apply(context || this, arguments)
      fn = null
    }

    return result
  }
}

export function once(fn, context){
  if (arguments.length === 1){
    const wrap = onceFn(fn, context)

    return curry(wrap)
  }

  return onceFn(fn, context)
}
Tests
import { once } from './once.js'

test('with counter', () => {
  let counter = 0
  const runOnce = once(x => {
    counter++

    return x + 2
  })
  expect(runOnce(1)).toBe(3)
  runOnce(1)
  runOnce(1)
  runOnce(1)
  expect(counter).toBe(1)
})

test('happy path', () => {
  const addOneOnce = once((
    a, b, c
  ) => a + b + c, 1)

  expect(addOneOnce(
    10, 20, 30
  )).toBe(60)
  expect(addOneOnce(40)).toBe(60)
})

test('with context', () => {
  const context = { name: 'fris' }
  const getNameOnce = once(function (){
    return this.name
  }, context)

  expect(getNameOnce()).toBe('fris')
  expect(getNameOnce()).toBe('fris')
  expect(getNameOnce()).toBe('fris')
})

---------------

or

or<T, U>(a: T, b: U): T | U

Logical OR

R.or(false, true); // => true
R.or(false, false); // => false
R.or(false, 'foo'); // => 'foo'

Try this R.or example in Rambda REPL

All TypeScript definitions
or<T, U>(a: T, b: U): T | U;
or<T>(a: T): <U>(b: U) => T | U;
R.or source
export function or(a, b){
  if (arguments.length === 1) return _b => or(a, _b)

  return a || b
}
Tests
import { or } from './or.js'

test('happy', () => {
  expect(or(0, 'foo')).toBe('foo')
  expect(or(true, true)).toBeTrue()
  expect(or(false)(true)).toBeTrue()
  expect(or(false, false)).toBeFalse()
})

---------------

over

over<S, A>(lens: Lens<S, A>): {
  (fn: (a: A) => A): (value: S) => S

It returns a copied Object or Array with modified value received by applying function fn to lens focus.

const headLens = R.lensIndex(0)
 
R.over(headLens, R.toUpper, ['foo', 'bar', 'baz']) // => ['FOO', 'bar', 'baz']

Try this R.over example in Rambda REPL

All TypeScript definitions
over<S, A>(lens: Lens<S, A>): {
  (fn: (a: A) => A): (value: S) => S;
  (fn: (a: A) => A, value: S): S;
};
over<S, A>(lens: Lens<S, A>, fn: (a: A) => A): (value: S) => S;
over<S, A>(lens: Lens<S, A>, fn: (a: A) => A, value: S): S;
R.over source
import { curry } from './curry.js'

const Identity = x => ({
  x,
  map : fn => Identity(fn(x)),
})

function overFn(
  lens, fn, object
){
  return lens(x => Identity(fn(x)))(object).x
}

export const over = curry(overFn)
Tests
import { assoc } from './assoc.js'
import { lens } from './lens.js'
import { lensIndex } from './lensIndex.js'
import { lensPath } from './lensPath.js'
import { over } from './over.js'
import { prop } from './prop.js'
import { toUpper } from './toUpper.js'

const testObject = {
  foo : 'bar',
  baz : {
    a : 'x',
    b : 'y',
  },
}

test('assoc lens', () => {
  const assocLens = lens(prop('foo'), assoc('foo'))
  const result = over(
    assocLens, toUpper, testObject
  )
  const expected = {
    ...testObject,
    foo : 'BAR',
  }
  expect(result).toEqual(expected)
})

test('path lens', () => {
  const pathLens = lensPath('baz.a')
  const result = over(
    pathLens, toUpper, testObject
  )
  const expected = {
    ...testObject,
    baz : {
      a : 'X',
      b : 'y',
    },
  }
  expect(result).toEqual(expected)
})

test('index lens', () => {
  const indexLens = lensIndex(0)
  const result = over(indexLens, toUpper)([ 'foo', 'bar' ])
  expect(result).toEqual([ 'FOO', 'bar' ])
})

---------------

partial

partial<V0, V1, T>(fn: (x0: V0, x1: V1) => T, args: [V0]): (x1: V1) => T

It is very similar to R.curry, but you can pass initial arguments when you create the curried function.

R.partial will keep returning a function until all the arguments that the function fn expects are passed. The name comes from the fact that you partially inject the inputs.

💥 Rambda's partial doesn't need the input arguments to be wrapped as array.

const fn = (title, firstName, lastName) => {
  return title + ' ' + firstName + ' ' + lastName + '!'
}

const canPassAnyNumberOfArguments = R.partial(fn, 'Hello')
const ramdaStyle = R.partial(fn, ['Hello'])

const finalFn = canPassAnyNumberOfArguments('Foo')

finalFn('Bar') // =>  'Hello, Foo Bar!'

Try this R.partial example in Rambda REPL

All TypeScript definitions
partial<V0, V1, T>(fn: (x0: V0, x1: V1) => T, args: [V0]): (x1: V1) => T;
partial<V0, V1, V2, T>(fn: (x0: V0, x1: V1, x2: V2) => T, args: [V0, V1]): (x2: V2) => T;
partial<V0, V1, V2, T>(fn: (x0: V0, x1: V1, x2: V2) => T, args: [V0]): (x1: V1, x2: V2) => T;
partial<V0, V1, V2, V3, T>(
  fn: (x0: V0, x1: V1, x2: V2, x3: V3) => T,
  args: [V0, V1, V2],
): (x2: V3) => T;
partial<V0, V1, V2, V3, T>(
  fn: (x0: V0, x1: V1, x2: V2, x3: V3) => T,
  args: [V0, V1],
): (x2: V2, x3: V3) => T;
partial<V0, V1, V2, V3, T>(
  fn: (x0: V0, x1: V1, x2: V2, x3: V3) => T,
  args: [V0],
): (x1: V1, x2: V2, x3: V3) => T;
partial<T>(fn: (...a: any[]) => T, args: any[]): (...a: any[]) => T;
R.partial source
import { isArray } from './_internals/isArray.js'

export function partial(fn, ...args){
  const len = fn.length

  // If a single array argument is given, those are the args (a la Ramda).
  // Otherwise, the variadic arguments are the args.
  const argList = args.length === 1 && isArray(args[0]) ? args[0] : args

  return (...rest) => {
    if (argList.length + rest.length >= len){
      return fn(...argList, ...rest)
    }

    return partial(fn, ...[ ...argList, ...rest ])
  }
}
Tests
import { partial } from './partial.js'
import { type } from './type.js'

const greet = (
  salutation, title, firstName, lastName
) =>
  [salutation, title, firstName, lastName]

test('happy', () => {
  const canPassAnyNumberOfArguments = partial(
    greet, 'Hello', 'Ms.'
  )
  const fn = canPassAnyNumberOfArguments('foo')
  const sayHello = partial(greet, [ 'Hello' ])
  const sayHelloRamda = partial(sayHello, [ 'Ms.' ])

  expect(type(fn)).toBe('Function')

  expect(fn('bar')).toStrictEqual(['Hello', 'Ms.', 'foo', 'bar'])
  expect(sayHelloRamda('foo', 'bar')).toStrictEqual(['Hello', 'Ms.', 'foo', 'bar'])
})

test('extra arguments are ignored', () => {
  const canPassAnyNumberOfArguments = partial(
    greet, 'Hello', 'Ms.'
  )
  const fn = canPassAnyNumberOfArguments('foo')

  expect(type(fn)).toBe('Function')

  expect(fn(
    'bar', 1, 2
  )).toStrictEqual(['Hello', 'Ms.', 'foo', 'bar'])
})

test('when array is input', () => {
  const fooFn = (
    a, b, c, d
  ) => ({
    a,
    b,
    c,
    d,
  })
  const barFn = partial(
    fooFn, [ 1, 2 ], []
  )

  expect(barFn(1, 2)).toEqual({
    a : [ 1, 2 ],
    b : [],
    c : 1,
    d : 2,
  })
})

test('ramda spec', () => {
  const sayHello = partial(greet, 'Hello')
  const sayHelloToMs = partial(sayHello, 'Ms.')

  expect(sayHelloToMs('Jane', 'Jones')).toStrictEqual(['Hello', 'Ms.', 'Jane', 'Jones'])
})

---------------

partialCurry

partialCurry<Input, PartialInput, Output>(
  fn: (input: Input) => Output, 
  partialInput: PartialInput,
): (input: Pick<Input, Exclude<keyof Input, keyof PartialInput>>) => Output

Same as R.partialObject.

When Ramda introduced R.partialObject, Rambdax already had such method, i.e. R.partialCurry. So this method is kept for backward compatibility.

💥 Function input can be asynchronous

All TypeScript definitions
partialCurry<Input, PartialInput, Output>(
  fn: (input: Input) => Output, 
  partialInput: PartialInput,
): (input: Pick<Input, Exclude<keyof Input, keyof PartialInput>>) => Output;
R.partialCurry source
export { partialObject as partialCurry } from './partialObject.js'

---------------

partialObject

partialObject<Input, PartialInput, Output>(
  fn: (input: Input) => Output, 
  partialInput: PartialInput,
): (input: Pick<Input, Exclude<keyof Input, keyof PartialInput>>) => Output

R.partialObject is a curry helper designed specifically for functions accepting object as a single argument.

Initially the function knows only a part from the whole input object and then R.partialObject helps in preparing the function for the second part, when it receives the rest of the input.

💥 Function input can be asynchronous

const fn = ({ a, b, c }) => a + b + c
const curried = R.partialObject(fn, { a : 1 })
const result = curried({
  b : 2,
  c : 3,
})
// => 6

Try this R.partialObject example in Rambda REPL

All TypeScript definitions
partialObject<Input, PartialInput, Output>(
  fn: (input: Input) => Output, 
  partialInput: PartialInput,
): (input: Pick<Input, Exclude<keyof Input, keyof PartialInput>>) => Output;
R.partialObject source
import { mergeDeepRight } from './mergeDeepRight.js'

export function partialObject(fn, input){
  return nextInput => fn(mergeDeepRight(nextInput, input))
}
Tests
import { delay } from './delay.js'
import { partialObject } from './partialObject.js'
import { type } from './type.js'

test('with plain function', () => {
  const fn = ({ a, b, c }) => a + b + c
  const curried = partialObject(fn, { a : 1 })

  expect(type(curried)).toBe('Function')
  expect(curried({
    b : 2,
    c : 3,
  })).toBe(6)
})

test('with function that throws an error', () => {
  const fn = ({ a, b, c }) => {
    throw new Error('foo')
  }
  const curried = partialObject(fn, { a : 1 })

  expect(type(curried)).toBe('Function')
  expect(() =>
    curried({
      b : 2,
      c : 3,
    })).toThrowErrorMatchingInlineSnapshot('"foo"')
})

test('with async', async () => {
  const fn = async ({ a, b, c }) => {
    await delay(100)

    return a + b + c
  }

  const curried = partialObject(fn, { a : 1 })

  const result = await curried({
    b : 2,
    c : 3,
  })

  expect(result).toBe(6)
})

test('async function throwing an error', async () => {
  const fn = async ({ a, b, c }) => {
    await delay(100)
    throw new Error('foo')
  }

  const curried = partialObject(fn, { a : 1 })

  try {
    await curried({
      b : 2,
      c : 3,
    })
    expect(true).toBeFalsy()
  } catch (e){
    expect(e.message).toBe('foo')
  }
})

---------------

partition

partition<T>(
  predicate: Predicate<T>,
  input: T[]
): [T[], T[]]

It will return array of two objects/arrays according to predicate function. The first member holds all instances of input that pass the predicate function, while the second member - those who doesn't.

const list = [1, 2, 3]
const obj = {a: 1, b: 2, c: 3}
const predicate = x => x > 2

const result = [
  R.partition(predicate, list),
  R.partition(predicate, Record<string, unknown>)
]
const expected = [
  [[3], [1, 2]],
  [{c: 3},  {a: 1, b: 2}],
]
// `result` is equal to `expected`

Try this R.partition example in Rambda REPL

All TypeScript definitions
partition<T>(
  predicate: Predicate<T>,
  input: T[]
): [T[], T[]];
partition<T>(
  predicate: Predicate<T>
): (input: T[]) => [T[], T[]];
partition<T>(
  predicate: (x: T, prop?: string) => boolean,
  input: { [key: string]: T}
): [{ [key: string]: T}, { [key: string]: T}];
partition<T>(
  predicate: (x: T, prop?: string) => boolean
): (input: { [key: string]: T}) => [{ [key: string]: T}, { [key: string]: T}];
R.partition source
import { isArray } from './_internals/isArray.js'

export function partitionObject(predicate, iterable){
  const yes = {}
  const no = {}
  Object.entries(iterable).forEach(([ prop, value ]) => {
    if (predicate(value, prop)){
      yes[ prop ] = value
    } else {
      no[ prop ] = value
    }
  })

  return [ yes, no ]
}

export function partitionArray(
  predicate, list, indexed = false
){
  const yes = []
  const no = []
  let counter = -1

  while (counter++ < list.length - 1){
    if (
      indexed ? predicate(list[ counter ], counter) : predicate(list[ counter ])
    ){
      yes.push(list[ counter ])
    } else {
      no.push(list[ counter ])
    }
  }

  return [ yes, no ]
}

export function partition(predicate, iterable){
  if (arguments.length === 1){
    return listHolder => partition(predicate, listHolder)
  }
  if (!isArray(iterable)) return partitionObject(predicate, iterable)

  return partitionArray(predicate, iterable)
}
Tests
import { partition } from './partition.js'

test('with array', () => {
  const predicate = x => x > 2
  const list = [ 1, 2, 3, 4 ]

  const result = partition(predicate, list)
  const expectedResult = [
    [ 3, 4 ],
    [ 1, 2 ],
  ]

  expect(result).toEqual(expectedResult)
})

test('with object', () => {
  const predicate = (value, prop) => {
    expect(typeof prop).toBe('string')

    return value > 2
  }
  const hash = {
    a : 1,
    b : 2,
    c : 3,
    d : 4,
  }

  const result = partition(predicate)(hash)
  const expectedResult = [
    {
      c : 3,
      d : 4,
    },
    {
      a : 1,
      b : 2,
    },
  ]

  expect(result).toEqual(expectedResult)
})

test('readme example', () => {
  const list = [ 1, 2, 3 ]
  const obj = {
    a : 1,
    b : 2,
    c : 3,
  }
  const predicate = x => x > 2

  const result = [ partition(predicate, list), partition(predicate, obj) ]
  const expected = [
    [ [ 3 ], [ 1, 2 ] ],
    [
      { c : 3 },
      {
        a : 1,
        b : 2,
      },
    ],
  ]
  expect(result).toEqual(expected)
})

---------------

partitionIndexed

partitionIndexed<T>(
  predicate: IndexedPredicate<T>,
  input: T[]
): [T[], T[]]
All TypeScript definitions
partitionIndexed<T>(
  predicate: IndexedPredicate<T>,
  input: T[]
): [T[], T[]];
partitionIndexed<T>(
  predicate: IndexedPredicate<T>
): (input: T[]) => [T[], T[]];
partitionIndexed<T>(
  predicate: (x: T, prop?: string) => boolean,
  input: { [key: string]: T}
): [{ [key: string]: T}, { [key: string]: T}];
partitionIndexed<T>(
  predicate: (x: T, prop?: string) => boolean
): (input: { [key: string]: T}) => [{ [key: string]: T}, { [key: string]: T}];
R.partitionIndexed source
import { isArray } from './_internals/isArray.js'
import { partitionArray, partitionObject } from './partition.js'

export function partitionIndexed(predicate, iterable){
  if (arguments.length === 1){
    return listHolder => partitionIndexed(predicate, listHolder)
  }
  if (!isArray(iterable)) return partitionObject(predicate, iterable)

  return partitionArray(
    predicate, iterable, true
  )
}
Tests
import { partitionIndexed } from './partitionIndexed.js'

test('with array', () => {
  const predicate = (x, i) => {
    expect(x).toBeNumber()

    return x > 2
  }
  const list = [ 1, 2, 3, 4 ]

  const result = partitionIndexed(predicate, list)
  const curried = partitionIndexed(predicate)(list)
  const expectedResult = [
    [ 3, 4 ],
    [ 1, 2 ],
  ]

  expect(result).toEqual(expectedResult)
  expect(curried).toEqual(expectedResult)
})

---------------

pass

pass(...inputs: any[]): (...rules: any[]) => boolean

It checks if inputs are following schemas specifications according to R.isValid.

const result = R.pass(
  1,
  ['foo','bar']
)(
  Number,
  [String]
)
// => true

Try this R.pass example in Rambda REPL

All TypeScript definitions
pass(...inputs: any[]): (...rules: any[]) => boolean;
R.pass source
import { any } from './any.js'
import { check } from './ok.js'

export function pass(...inputs){
  return (...schemas) =>
    any((x, i) => {
      const schema = schemas[ i ] === undefined ? schemas[ 0 ] : schemas[ i ]

      return !check(x, schema)
    }, inputs) === false
}
Tests
import { pass } from './pass.js'

test('true on success', () => {
  const result = pass(
    1, 'foo', {}
  )(
    'number', 'string', 'object'
  )

  expect(result).toBeTrue()
})

test('false on failure', () => {
  expect(pass(
    1, 'foo', {}
  )(
    'number', 'string', 'string'
  )).toBeFalse()
})

test('true when single schema', () => {
  expect(pass(
    1, 2, 3
  )('number')).toBeTrue()
})

test('false when single schema', () => {
  expect(pass(
    1, 'foo', {}
  )('number')).toBeFalse()
})

test('array of schemas', () => {
  const result = pass([ { a : 1 }, { a : 2 }, { a : 3 } ])([ { a : Number } ])
  expect(result).toBeTruthy()
})

test('reame example', () => {
  const result = pass(1, [ 'foo', 'bar' ])(Number, [ String ])
  expect(result).toBeTruthy()
})

---------------

path

path<S, K0 extends keyof S = keyof S>(path: [K0], obj: S): S[K0]

If pathToSearch is 'a.b' then it will return 1 if obj is {a:{b:1}}.

It will return undefined, if such path is not found.

💥 String annotation of pathToSearch is one of the differences between Rambda and Ramda.

const obj = {a: {b: 1}}
const pathToSearch = 'a.b'
const pathToSearchList = ['a', 'b']

const result = [
  R.path(pathToSearch, obj),
  R.path(pathToSearchList, obj),
  R.path('a.b.c.d', obj)
]
// => [1, 1, undefined]

Try this R.path example in Rambda REPL

All TypeScript definitions
path<S, K0 extends keyof S = keyof S>(path: [K0], obj: S): S[K0];
path<S, K0 extends keyof S = keyof S, K1 extends keyof S[K0] = keyof S[K0]>(path: [K0, K1], obj: S): S[K0][K1];
path<
    S,
    K0 extends keyof S = keyof S,
    K1 extends keyof S[K0] = keyof S[K0],
    K2 extends keyof S[K0][K1] = keyof S[K0][K1]
>(path: [K0, K1, K2], obj: S): S[K0][K1][K2];
path<
    S,
    K0 extends keyof S = keyof S,
    K1 extends keyof S[K0] = keyof S[K0],
    K2 extends keyof S[K0][K1] = keyof S[K0][K1],
    K3 extends keyof S[K0][K1][K2] = keyof S[K0][K1][K2],
>(path: [K0, K1, K2, K3], obj: S): S[K0][K1][K2][K3];
path<
    S,
    K0 extends keyof S = keyof S,
    K1 extends keyof S[K0] = keyof S[K0],
    K2 extends keyof S[K0][K1] = keyof S[K0][K1],
    K3 extends keyof S[K0][K1][K2] = keyof S[K0][K1][K2],
    K4 extends keyof S[K0][K1][K2][K3] = keyof S[K0][K1][K2][K3],
>(path: [K0, K1, K2, K3, K4], obj: S): S[K0][K1][K2][K3][K4];
path<
    S,
    K0 extends keyof S = keyof S,
    K1 extends keyof S[K0] = keyof S[K0],
    K2 extends keyof S[K0][K1] = keyof S[K0][K1],
    K3 extends keyof S[K0][K1][K2] = keyof S[K0][K1][K2],
    K4 extends keyof S[K0][K1][K2][K3] = keyof S[K0][K1][K2][K3],
    K5 extends keyof S[K0][K1][K2][K3][K4] = keyof S[K0][K1][K2][K3][K4],
>(path: [K0, K1, K2, K3, K4, K5], obj: S): S[K0][K1][K2][K3][K4][K5];
path<T>(pathToSearch: string, obj: any): T | undefined;
path<T>(pathToSearch: string): (obj: any) => T | undefined;
path<T>(pathToSearch: RamdaPath): (obj: any) => T | undefined;
path<T>(pathToSearch: RamdaPath, obj: any): T | undefined;
R.path source
import { createPath } from './_internals/createPath.js'

export function pathFn(pathInput, obj){
  let willReturn = obj
  let counter = 0

  const pathArrValue = createPath(pathInput)

  while (counter < pathArrValue.length){
    if (willReturn === null || willReturn === undefined){
      return undefined
    }
    if (willReturn[ pathArrValue[ counter ] ] === null) return undefined

    willReturn = willReturn[ pathArrValue[ counter ] ]
    counter++
  }

  return willReturn
}

export function path(pathInput, obj){
  if (arguments.length === 1) return _obj => path(pathInput, _obj)

  if (obj === null || obj === undefined){
    return undefined
  }

  return pathFn(pathInput, obj)
}
Tests
import { path } from './path.js'

test('with array inside object', () => {
  const obj = { a : { b : [ 1, { c : 1 } ] } }

  expect(path('a.b.1.c', obj)).toBe(1)
})

test('works with undefined', () => {
  const obj = { a : { b : { c : 1 } } }

  expect(path('a.b.c.d.f', obj)).toBeUndefined()
  expect(path('foo.babaz', undefined)).toBeUndefined()
  expect(path('foo.babaz')(undefined)).toBeUndefined()
})

test('works with string instead of array', () => {
  expect(path('foo.bar.baz')({ foo : { bar : { baz : 'yes' } } })).toBe('yes')
})

test('path', () => {
  expect(path([ 'foo', 'bar', 'baz' ])({ foo : { bar : { baz : 'yes' } } })).toBe('yes')
  expect(path([ 'foo', 'bar', 'baz' ])(null)).toBeUndefined()
  expect(path([ 'foo', 'bar', 'baz' ])({ foo : { bar : 'baz' } })).toBeUndefined()
})

test('with number string in between', () => {
	expect(path(['a','1','b'], {a: [{b: 1}, {b: 2}]})).toBe(2)
})

test('null is not a valid path', () => {
  expect(path('audio_tracks', {
    a            : 1,
    audio_tracks : null,
  })).toBeUndefined()
})

---------------

pathEq

pathEq(pathToSearch: Path, target: any, input: any): boolean

It returns true if pathToSearch of input object is equal to target value.

pathToSearch is passed to R.path, which means that it can be either a string or an array. Also equality between target and the found value is determined by R.equals.

const path = 'a.b'
const target = {c: 1}
const input = {a: {b: {c: 1}}}

const result = R.pathEq(
  path,
  target,
  input
)
// => true

Try this R.pathEq example in Rambda REPL

All TypeScript definitions
pathEq(pathToSearch: Path, target: any, input: any): boolean;
pathEq(pathToSearch: Path, target: any): (input: any) => boolean;
pathEq(pathToSearch: Path): (target: any) => (input: any) => boolean;
R.pathEq source
import { curry } from './curry.js'
import { equals } from './equals.js'
import { path } from './path.js'

function pathEqFn(
  pathToSearch, target, input
){
  return equals(path(pathToSearch, input), target)
}

export const pathEq = curry(pathEqFn)
Tests
import { pathEq } from './pathEq.js'

test('when true', () => {
  const path = 'a.b'
  const obj = { a : { b : { c : 1 } } }
  const target = { c : 1 }

  expect(pathEq(
    path, target, obj
  )).toBeTrue()
})

test('when false', () => {
  const path = 'a.b'
  const obj = { a : { b : 1 } }
  const target = 2

  expect(pathEq(path, target)(obj)).toBeFalse()
})

test('when wrong path', () => {
  const path = 'foo.bar'
  const obj = { a : { b : 1 } }
  const target = 2

  expect(pathEq(
    path, target, obj
  )).toBeFalse()
})

---------------

pathOr

pathOr<T>(defaultValue: T, pathToSearch: Path, obj: any): T

It reads obj input and returns either R.path(pathToSearch, Record<string, unknown>) result or defaultValue input.

const defaultValue = 'DEFAULT_VALUE'
const pathToSearch = 'a.b'
const pathToSearchList = ['a', 'b']

const obj = {
  a : {
    b : 1
  }
}

const result = [
  R.pathOr(DEFAULT_VALUE, pathToSearch, Record<string, unknown>),
  R.pathOr(DEFAULT_VALUE, pathToSearchList, Record<string, unknown>), 
  R.pathOr(DEFAULT_VALUE, 'a.b.c', Record<string, unknown>)
]
// => [1, 1, 'DEFAULT_VALUE']

Try this R.pathOr example in Rambda REPL

All TypeScript definitions
pathOr<T>(defaultValue: T, pathToSearch: Path, obj: any): T;
pathOr<T>(defaultValue: T, pathToSearch: Path): (obj: any) => T;
pathOr<T>(defaultValue: T): (pathToSearch: Path) => (obj: any) => T;
R.pathOr source
import { curry } from './curry.js'
import { defaultTo } from './defaultTo.js'
import { path } from './path.js'

function pathOrFn(
  defaultValue, pathInput, obj
){
  return defaultTo(defaultValue, path(pathInput, obj))
}

export const pathOr = curry(pathOrFn)
Tests
import { pathOr } from './pathOr.js'

test('with undefined', () => {
  const result = pathOr(
    'foo', 'x.y', { x : { y : 1 } }
  )

  expect(result).toBe(1)
})

test('with null', () => {
  const result = pathOr(
    'foo', 'x.y', null
  )

  expect(result).toBe('foo')
})

test('with NaN', () => {
  const result = pathOr(
    'foo', 'x.y', NaN
  )

  expect(result).toBe('foo')
})

test('curry case (x)(y)(z)', () => {
  const result = pathOr('foo')('x.y.z')({ x : { y : { a : 1 } } })

  expect(result).toBe('foo')
})

test('curry case (x)(y,z)', () => {
  const result = pathOr('foo', 'x.y.z')({ x : { y : { a : 1 } } })

  expect(result).toBe('foo')
})

test('curry case (x,y)(z)', () => {
  const result = pathOr('foo')('x.y.z', { x : { y : { a : 1 } } })

  expect(result).toBe('foo')
})

---------------

paths

paths<Input, T>(pathsToSearch: Path[], obj: Input): (T | undefined)[]

It loops over members of pathsToSearch as singlePath and returns the array produced by R.path(singlePath, Record<string, unknown>).

Because it calls R.path, then singlePath can be either string or a list.

const obj = {
  a : {
    b : {
      c : 1,
      d : 2
    }
  }
}

const result = R.paths([
  'a.b.c',
  'a.b.d',
  'a.b.c.d.e',
], Record<string, unknown>)
// => [1, 2, undefined]

Try this R.paths example in Rambda REPL

All TypeScript definitions
paths<Input, T>(pathsToSearch: Path[], obj: Input): (T | undefined)[];
paths<Input, T>(pathsToSearch: Path[]): (obj: Input) => (T | undefined)[];
paths<T>(pathsToSearch: Path[], obj: any): (T | undefined)[];
paths<T>(pathsToSearch: Path[]): (obj: any) => (T | undefined)[];
R.paths source
import { path } from './path.js'

export function paths(pathsToSearch, obj){
  if (arguments.length === 1){
    return _obj => paths(pathsToSearch, _obj)
  }

  return pathsToSearch.map(singlePath => path(singlePath, obj))
}
Tests
import { paths } from './paths.js'

const obj = {
  a : {
    b : {
      c : 1,
      d : 2,
    },
  },
  p : [ { q : 3 } ],
  x : {
    y : 'FOO',
    z : [ [ {} ] ],
  },
}

test('with string path + curry', () => {
  const pathsInput = [ 'a.b.d', 'p.q' ]
  const expected = [ 2, undefined ]
  const result = paths(pathsInput, obj)
  const curriedResult = paths(pathsInput)(obj)

  expect(result).toEqual(expected)
  expect(curriedResult).toEqual(expected)
})

test('with array path', () => {
  const result = paths([
    [ 'a', 'b', 'c' ],
    [ 'x', 'y' ],
  ],
  obj)

  expect(result).toEqual([ 1, 'FOO' ])
})

test('takes a paths that contains indices into arrays', () => {
  expect(paths([
    [ 'p', 0, 'q' ],
    [ 'x', 'z', 0, 0 ],
  ],
  obj)).toEqual([ 3, {} ])
  expect(paths([
    [ 'p', 0, 'q' ],
    [ 'x', 'z', 2, 1 ],
  ],
  obj)).toEqual([ 3, undefined ])
})

test('gets a deep property\'s value from objects', () => {
  expect(paths([ [ 'a', 'b' ] ], obj)).toEqual([ obj.a.b ])
  expect(paths([ [ 'p', 0 ] ], obj)).toEqual([ obj.p[ 0 ] ])
})

test('returns undefined for items not found', () => {
  expect(paths([ [ 'a', 'x', 'y' ] ], obj)).toEqual([ undefined ])
  expect(paths([ [ 'p', 2 ] ], obj)).toEqual([ undefined ])
})

---------------

pathSatisfies

pathSatisfies<T, U>(pred: (val: T) => boolean, path: Path): (obj: U) => boolean
const result = R.pathSatisfies(
  x => x > 0,
  ['a', 'b', 'c'],
  {a: {b: {c: 1}}}
)
// => true

Try this R.pathSatisfies example in Rambda REPL

All TypeScript definitions
pathSatisfies<T, U>(pred: (val: T) => boolean, path: Path): (obj: U) => boolean;
pathSatisfies<T, U>(pred: (val: T) => boolean, path: Path, obj: U): boolean;
R.pathSatisfies source
import { path } from "./path.js";
import { curry } from "./curry.js";

export function pathSatisfiesFn(fn, pathInput, obj) {
  if(pathInput.length === 0) throw new Error("R.pathSatisfies received an empty path")
  return Boolean(fn(path(pathInput, obj))) 
}

export const pathSatisfies = curry(pathSatisfiesFn)
Tests
import { pathSatisfies } from './pathSatisfies';

const isPositive = (n) => n > 0;

it('returns true if the specified object path satisfies the given predicate', () => {
	expect(
		pathSatisfies(isPositive, ['x', 1, 'y'], { x: [{ y: -1 }, { y: 1 }] }),
	).toBe(true);
	expect(
		pathSatisfies(isPositive, 'x.1.y', { x: [{ y: -1 }, { y: 1 }] }),
	).toBe(true);
});

it('returns false if the specified path does not exist', () => {
	expect(pathSatisfies(isPositive, ['x', 'y'], { x: { z: 42 } })).toBe(false);
	expect(pathSatisfies(isPositive, 'x.y', { x: { z: 42 } })).toBe(false);
});

it('throws on empty paths', () => {
	expect(() => pathSatisfies(Object.is, [], { x: { z: 42 } })).toThrow();
});

it('returns false otherwise', () => {
	expect(pathSatisfies(isPositive, ['x', 'y'], { x: { y: 0 } })).toBe(false);
});

---------------

pick

pick<T, K extends string | number | symbol>(propsToPick: K[], input: T): Pick<T, Exclude<keyof T, Exclude<keyof T, K>>>

It returns a partial copy of an input containing only propsToPick properties.

input can be either an object or an array.

String annotation of propsToPick is one of the differences between Rambda and Ramda.

💥 When using this method with TypeScript, it is much easier to pass propsToPick as an array. If passing a string, you will need to explicitly declare the output type.

const obj = {
  a : 1,
  b : false,
  foo: 'cherry'
}
const list = [1, 2, 3, 4]
const propsToPick = 'a,foo'
const propsToPickList = ['a', 'foo']

const result = [
  R.pick(propsToPick, Record<string, unknown>),
  R.pick(propsToPickList, Record<string, unknown>),
  R.pick('a,bar', Record<string, unknown>),
  R.pick('bar', Record<string, unknown>),
  R.pick([0, 3, 5], list),
  R.pick('0,3,5', list),
]

const expected = [
  {a:1, foo: 'cherry'},
  {a:1, foo: 'cherry'},
  {a:1},
  {},
  {0: 1, 3: 4},
  {0: 1, 3: 4},
]
// => `result` is equal to `expected`

Try this R.pick example in Rambda REPL

All TypeScript definitions
pick<T, K extends string | number | symbol>(propsToPick: K[], input: T): Pick<T, Exclude<keyof T, Exclude<keyof T, K>>>;
pick<K extends string | number | symbol>(propsToPick: K[]): <T>(input: T) => Pick<T, Exclude<keyof T, Exclude<keyof T, K>>>;
pick<T, U>(propsToPick: string, input: T): U;
pick<T, U>(propsToPick: string)