Faster and smaller alternative to Ramda

Overview

Rambda

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

CircleCI codecov dependencies Status Commit activity All contributors Library size

❯ Example use

import { compose, map, filter } from 'rambda'

const result = compose(
  map(x => x * 2),
  filter(x => x > 2)
)([1, 2, 3, 4])
// => [6, 8]

You can test this example in Rambda's REPL

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

❯ Rambda'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.

Smaller size

The size of a library affects not only the build bundle size but also the dev bundle size and build time. This is important advantage, expecially for big projects.

Tree-shaking

Currently Rambda is more tree-shakable than Ramda - proven in the following repo.

The repo holds two Angular9 applications: one with small example code of Ramda and the other - same code but with Rambda as import library.

The test shows that Rambda bundle size is 2.03 MB less than its Ramda counterpart.

There is also Webpack/Rollup/Parcel/Esbuild tree-shaking example including several libraries including Ramda, Rambda and Rambdax.

actually tree-shaking is the initial reason for creation of Rambda

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

Speed

Rambda is generally more performant than Ramda as the benchmarks can prove that.

Support

Most of the valid issues are fixed within 2-3 days.

Closing the issue is usually accompanied by publishing a new patch version of Rambda to NPM.

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

❯ Missing Ramda methods

Click to see the full list of 89 Ramda methods not implemented in Rambda
  • __
  • addIndex
  • ap
  • aperture
  • apply
  • applyTo
  • ascend
  • binary
  • bind
  • call
  • comparator
  • composeK
  • composeP
  • composeWith
  • construct
  • constructN
  • contains
  • countBy
  • descend
  • differenceWith
  • dissocPath
  • empty
  • eqBy
  • forEachObjIndexed
  • gt
  • gte
  • hasIn
  • innerJoin
  • insert
  • insertAll
  • into
  • invert
  • invertObj
  • invoker
  • juxt
  • keysIn
  • lift
  • liftN
  • lt
  • lte
  • mapAccum
  • mapAccumRight
  • mapObjIndexed
  • memoizeWith
  • mergeDeepLeft
  • mergeDeepWith
  • mergeDeepWithKey
  • mergeRight
  • mergeWith
  • mergeWithKey
  • nAry
  • nthArg
  • o
  • otherwise
  • pair
  • partialRight
  • pathSatisfies
  • pickBy
  • pipeK
  • pipeP
  • pipeWith
  • project
  • propSatisfies
  • reduceBy
  • reduceRight
  • reduceWhile
  • reduced
  • remove
  • scan
  • sequence
  • sortWith
  • symmetricDifferenceWith
  • andThen
  • toPairsIn
  • transduce
  • traverse
  • unapply
  • unary
  • uncurryN
  • unfold
  • unionWith
  • uniqBy
  • unnest
  • until
  • useWith
  • valuesIn
  • xprod
  • thunkify
  • default

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

❯ Install

  • yarn add rambda

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

https://unpkg.com/rambda@CURRENT_VERSION/dist/rambda.umd.js
  • with deno
import {compose, add} from 'https://raw.githubusercontent.com/selfrefactor/rambda/master/dist/rambda.esm.js'

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

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.

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

If you need more Ramda methods in Rambda, you may either submit a PR or check the extended version of Rambda - Rambdax. In case of the former, you may want to consult with Rambda contribution guidelines.

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

❯ 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.20) and Ramda(0.27.1).

method Rambda Ramda Lodash
add 96.25% slower 96.24% slower 🚀 Fastest
adjust 🚀 Fastest 5.52% slower 🔳
all 🚀 Fastest 94.95% slower 🔳
allPass 🚀 Fastest 98.95% slower 🔳
any 🚀 Fastest 98.18% slower 6.18% slower
anyPass 🚀 Fastest 99.09% slower 🔳
append 🚀 Fastest 84.09% slower 🔳
applySpec 🚀 Fastest 75.73% slower 🔳
assoc 87.98% slower 57.39% slower 🚀 Fastest
clone 🚀 Fastest 96.03% slower 91.75% slower
compose 🚀 Fastest 96.45% slower 77.83% slower
converge 49.12% slower 🚀 Fastest 🔳
curry 🚀 Fastest 34.9% slower 🔳
curryN 63.32% slower 🚀 Fastest 🔳
defaultTo 🚀 Fastest 50.3% slower 🔳
drop 🚀 Fastest 97.45% slower 🔳
dropLast 🚀 Fastest 97.07% slower 🔳
equals 72.11% slower 79.48% slower 🚀 Fastest
filter 🚀 Fastest 94.74% slower 58.18% slower
find 🚀 Fastest 98.2% slower 88.96% slower
findIndex 🚀 Fastest 97.97% slower 79.39% slower
flatten 6.56% slower 95.38% slower 🚀 Fastest
ifElse 🚀 Fastest 70.97% slower 🔳
includes 🚀 Fastest 71.7% slower 🔳
indexOf 🚀 Fastest 84.08% slower 7.86% slower
init 94.42% slower 97.55% slower 🚀 Fastest
is 🚀 Fastest 11.72% slower 🔳
isEmpty 51.68% slower 93.82% slower 🚀 Fastest
last 🚀 Fastest 99.64% slower 1.05% slower
lastIndexOf 🚀 Fastest 42.38% slower 🔳
map 🚀 Fastest 69.63% slower 4.68% slower
match 🚀 Fastest 46.75% slower 🔳
merge 63.55% slower 🚀 Fastest 55.25% slower
none 🚀 Fastest 98.22% slower 🔳
omit 🚀 Fastest 70.66% slower 97.56% slower
over 🚀 Fastest 50.77% slower 🔳
path 🚀 Fastest 74.94% slower 5.72% slower
pick 🚀 Fastest 26.29% slower 86.82% slower
prop 🚀 Fastest 89.89% slower 🔳
propEq 🚀 Fastest 95.26% slower 🔳
range 95.17% slower 90.22% slower 🚀 Fastest
reduce 52.76% slower 74.02% slower 🚀 Fastest
repeat 85.91% slower 95.31% slower 🚀 Fastest
replace 0.47% slower 28.13% slower 🚀 Fastest
set 🚀 Fastest 36.26% slower 🔳
sort 🚀 Fastest 63.15% slower 🔳
sortBy 🚀 Fastest 61.57% slower 88.88% slower
split 🚀 Fastest 85.34% slower 33.69% slower
splitEvery 🚀 Fastest 90.18% slower 🔳
take 93.44% slower 98.04% slower 🚀 Fastest
takeLast 92.61% slower 98.83% slower 🚀 Fastest
test 🚀 Fastest 94.42% slower 🔳
type 18.91% slower 🚀 Fastest 🔳
uniq 98.98% slower 96.58% slower 🚀 Fastest
update 🚀 Fastest 38.88% slower 🔳
view 🚀 Fastest 82.21% 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 } from './add'

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

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

test('ramda specs', () => {
  expect(add('1', '2')).toEqual(3)
  expect(add(1, '2')).toEqual(3)
  expect(add(true, false)).toEqual(1)
  expect(add(null, null)).toEqual(0)
  expect(add(undefined, undefined)).toEqual(NaN)
  expect(add(new Date(1), new Date(2))).toEqual(3)
})
Typescript test
import {add} from 'rambda'

describe('R.add', () => {
  it('happy', () => {
    const result = add(4, 1)

    result // $ExpectType number
  })
  it('curried', () => {
    const result = add(4)(1)

    result // $ExpectType number
  })
})
Lodash is fastest. Rambda is 96.25% slower and Ramda is 96.24% slower
const R = require('../../dist/rambda.js')

const add = [
  {
    label : 'Rambda',
    fn    : () => {
      R.add(1, 1)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.add(1, 1)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.add(1, 1)
    },
  },
]

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

adjust

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

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

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: readonly T[]): readonly T[];
adjust<T>(index: number, replaceFn: (x: T) => T): (list: readonly T[]) => readonly T[];
R.adjust source
import { curry } from './curry'

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

  const clone = list.slice()
  clone[ actualIndex ] = replaceFn(clone[ actualIndex ])

  return clone
}

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

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)
})
Rambda is faster than Ramda with 5.52%
const R = require('../../dist/rambda.js')

const list = [ 0, 1, 2 ]
const fn = x => x + 1
const index = 1

const adjust = [
  {
    label : 'Rambda',
    fn    : () => {
      R.adjust(
        index, fn, list
      )
      R.adjust(index, fn)(list)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.adjust(
        index, fn, list
      )
      Ramda.adjust(index, fn)(list)
    },
  },
]

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

all

all<T>(predicate: (x: T) => boolean, list: readonly 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: readonly T[]): boolean;
all<T>(predicate: (x: T) => boolean): (list: readonly 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'

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()
})
Typescript test
import {all} from 'rambda'

describe('all', () => {
  it('happy', () => {
    const result = all(
      x => {
        x // $ExpectType number
        return x > 0
      },
      [1, 2, 3]
    )
    result // $ExpectType boolean
  })
  it('curried needs a type', () => {
    const result = all<number>(x => {
      x // $ExpectType number
      return x > 0
    })([1, 2, 3])
    result // $ExpectType boolean
  })
})
Rambda is faster than Ramda with 94.95%
const R = require('../../dist/rambda.js')

const input = [ 1, 2, 3, 4 ]

const all = [
  {
    label : 'Rambda',
    fn    : () => {
      const fn = x => x > 2

      R.all(fn, input)
      R.all(fn)(input)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      const fn = x => x > 2

      Ramda.all(fn, input)
      Ramda.all(fn)(input)
    },
  },
]

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

allPass

allPass<T>(predicates: readonly ((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: readonly ((x: T) => boolean)[]): (input: 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'

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()
})
Typescript test
import {allPass} from 'rambda'

describe('allPass', () => {
  it('happy', () => {
    const x = allPass<number>([
      y => {
        y // $ExpectType number
        return typeof y === 'number'
      },
      y => {
        return y > 0
      },
    ])(11)

    x // $ExpectType boolean
  })
})
Rambda is faster than Ramda with 98.95%
const R = require('../../dist/rambda.js')

const rules = [ x => typeof x === 'number', x => x > 10, x => x * 7 < 100 ]

const allPass = [
  {
    label : 'Rambda',
    fn    : () => {
      R.allPass(rules)(11)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.allPass(rules)(11)
    },
  },
]

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

always

always<T>(x: T): () => T

It returns function that always returns x.

const fn = R.always(7)

console.log(fn())// => 7

Try this R.always example in Rambda REPL

All Typescript definitions
always<T>(x: T): () => T;
R.always source
export function always(x){
  return () => x
}
Tests
import { always } from './always'
import { F } from './F'

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

  expect(fn()).toEqual(7)
  expect(fn()).toEqual(7)
})

test('f', () => {
  const fn = always(F())

  expect(fn()).toBeFalse()
  expect(fn()).toBeFalse()
})
Typescript test
import {always} from 'rambda'

describe('R.always', () => {
  it('happy', () => {
    const fn = always('foo')
    fn // $ExpectType () => string
    const result = fn()
    result // $ExpectType string
  })
})

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

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'

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()
})
Typescript test
import {and} from 'rambda'

describe('R.and', () => {
  it('happy', () => {
    const result = and(true, false)
    result // $ExpectType boolean
  })
  it('curried', () => {
    const result = and('foo')(1)
    result // $ExpectType string | 1
  })
})
const R = require('../../dist/rambda.js')

const and = [
  {
    label : 'Rambda',
    fn    : () => {
      R.and(true, true)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.and(true, true)
    },
  },
]

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

any

any<T>(predicate: (x: T) => boolean, list: readonly 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: readonly T[]): boolean;
any<T>(predicate: (x: T) => boolean): (list: readonly 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'

const list = [ 1, 2, 3 ]

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

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

describe('R.any', () => {
  it('happy', () => {
    const result = any(
      x => {
        x // $ExpectType number
        return x > 2
      },
      [1, 2, 3]
    )
    result // $ExpectType boolean
  })

  it('when curried needs a type', () => {
    const result = any<number>(x => {
      x // $ExpectType number
      return x > 2
    })([1, 2, 3])
    result // $ExpectType boolean
  })
})
Rambda is fastest. Ramda is 98.18% slower and Lodash is 6.18% slower
const R = require('../../dist/rambda.js')

const input = [ 1, 2, 3, 4 ]
const fn = val => val > 2

const any = [
  {
    label : 'Rambda',
    fn    : () => {
      R.any(fn, input)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.any(fn, input)
    },
  },
  {
    label : 'Lodash.some',
    fn    : () => {
      _.some(input, fn)
    },
  },
]

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

anyPass

anyPass<T>(predicates: readonly SafePred<T>[]): SafePred<T>

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: readonly SafePred<T>[]): SafePred<T>;
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'

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('happy', () => {
  expect(anyPass([])(3)).toEqual(false)
})
Typescript test
import {anyPass} from 'rambda'

describe('anyPass', () => {
  it('happy', () => {
    const x = anyPass<number>([
      y => {
        y // $ExpectType number
        return typeof y === 'number'
      },
      y => {
        return y > 0
      },
    ])(11)

    x // $ExpectType boolean
  })
})
Rambda is faster than Ramda with 99.09%
const R = require('../../dist/rambda.js')

const rules = [ x => typeof x === 'boolean', x => x > 20, x => x * 7 < 100 ]

const anyPass = [
  {
    label : 'Rambda',
    fn    : () => {
      R.anyPass(rules)(11)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.anyPass(rules)(11)
    },
  },
]

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

append

append<T>(x: T, list: readonly T[]): readonly T[]

It adds element x at the end of list.

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>(x: T, list: readonly T[]): readonly T[];
append<T>(x: T): <T>(list: readonly T[]) => readonly T[];
R.append source
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 = input.slice()
  clone.push(x)

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

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' ])
})
Typescript test
import {append} from 'rambda'

const list = [1, 2, 3]

describe('R.append', () => {
  it('happy', () => {
    const result = append(4, list)

    result // $ExpectType number[]
  })
  it('curried', () => {
    const result = append(4)(list)

    result // $ExpectType number[]
  })
})
Rambda is faster than Ramda with 84.09%
const R = require('../../dist/rambda.js')

const append = [
  {
    label : 'Rambda',
    fn    : () => {
      R.append(0)([ 1, 2, 3, 4 ])
      R.append('bar')('foo')
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.append(0)([ 1, 2, 3, 4 ])
      Ramda.append('bar')('foo')
    },
  },
]

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

applySpec

applySpec<Spec extends Record<string, (...args: readonly any[]) => any>>(
  spec: Spec
): (
  ...args: Parameters<ValueOfRecord<Spec>>
) => { readonly [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, (...args: readonly any[]) => any>>(
  spec: Spec
): (
  ...args: Parameters<ValueOfRecord<Spec>>
) => { readonly [Key in keyof Spec]: ReturnType<Spec[Key]> };
applySpec<T>(spec: any): (...args: readonly any[]) => T;
R.applySpec source
import { _isArray } from './_internals/_isArray'

// recursively traverse the given spec object to find the highest arity function
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'
import { applySpec } from './applySpec'

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.length).toBe(0)
  expect(fRamda.length).toBe(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',
  })
})
Typescript test
import {multiply, applySpec, inc, dec, add} from 'rambda'

describe('applySpec', () => {
  it('ramda 1', () => {
    const result = applySpec({
      v: inc,
      u: dec,
    })(1)
    result // $ExpectType { v: number; u: number; }
  })
  it('ramda 1', () => {
    interface Output {
      sum: number,
      multiplied: number,
    }
    const result = applySpec<Output>({
      sum: add,
      multiplied: multiply,
    })(1, 2)

    result // $ExpectType Output
  })
})
Rambda is faster than Ramda with 75.73%
const R = require('../../dist/rambda.js')

const curryN = [
  {
    label : 'Rambda',
    fn    : () => {
      const data = {
        a : {
          b : { c : 1 },
          d : 2,
        },
      }
      const spec = {
        c : R.path([ 'a', 'b', 'c' ]),
        d : R.path([ 'a', 'd' ]),
      }
      R.applySpec(spec, data)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      const data = {
        a : {
          b : { c : 1 },
          d : 2,
        },
      }
      const spec = {
        c : Ramda.path([ 'a', 'b', 'c' ]),
        d : Ramda.path([ 'a', 'd' ]),
      }
      Ramda.applySpec(spec, data)
    },
  },
]

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

assoc

assoc<T, U, K extends string>(prop: K, val: T, obj: U): Record<K, T> & 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<T, U, K extends string>(prop: K, val: T, obj: U): Record<K, T> & U;
assoc<T, K extends string>(prop: K, val: T): <U>(obj: U) => Record<K, T> & U;
assoc<K extends string>(prop: K): AssocPartialOne<K>;
R.assoc source
import { curry } from './curry'

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

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

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 } })
})
Typescript test
import {assoc} from 'rambda'

const obj = {a: 1}
const newValue = 2
const newProp = 'b'

describe('R.assoc', () => {
  it('happy', () => {
    const result = assoc(newProp, newValue, obj)

    result.a // $ExpectType number
    result.b // $ExpectType number
  })
  it('curried 1', () => {
    const result = assoc(newProp, newValue)(obj)

    result.a // $ExpectType number
    result.b // $ExpectType number
  })
  it('curried 2', () => {
    const result = assoc(newProp)(newValue)(obj)

    result.a // $ExpectType number
    result.b // $ExpectType number
  })
})
Lodash is fastest. Rambda is 87.98% slower and Ramda is 57.39% slower
const R = require('../../dist/rambda.js')

const input = {
  a : 1,
  b : 2,
}
const key = 'c'
const value = 3

const assoc = [
  {
    label : 'Rambda',
    fn    : () => {
      R.assoc(
        key, value, input
      )
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.assoc(
        key, value, input
      )
    },
  },
  {
    label : 'Lodash.set',
    fn    : () => {
      _.set(
        input, key, value
      )
    },
  },
]

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

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 }

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 { _isArray } from './_internals/_isArray'
import { _isInteger } from './_internals/_isInteger'
import { assoc } from './assoc'
import { curry } from './curry'

function assocPathFn(
  path, newValue, input
){
  const pathArrValue =
    typeof path === 'string' ?
      path.split('.').map(x => _isInteger(Number(x)) ? Number(x) : x) :
      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 ?
      _isInteger(pathArrValue[ 1 ]) ?
        [] :
        {} :
      input[ index ]

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

  if (_isInteger(index) && _isArray(input)){
    const arr = input.slice()
    arr[ index ] = newValue

    return arr
  }

  return assoc(
    index, newValue, input
  )
}

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

test('string can be used as path input', () => {
  const testObj = {
    a : [ { b : 1 }, { b : 2 } ],
    d : 3,
  }
  const result = assocPath(
    'a.0.b', 10, testObj
  )
  const expected = {
    a : [ { b : 10 }, { b : 2 } ],
    d : 3,
  }
  expect(result).toEqual(expected)
})

test('bug', () => {
  /*
    https://github.com/selfrefactor/rambda/issues/524
  */
  const state = {}

  const withDateLike = assocPath(
    [ 'outerProp', '2020-03-10' ],
    { prop : 2 },
    state
  )
  const withNumber = assocPath(
    [ 'outerProp', '5' ], { prop : 2 }, state
  )

  const withDateLikeExpected = { outerProp : { '2020-03-10' : { prop : 2 } } }
  const withNumberExpected = { outerProp : { 5 : { prop : 2 } } }
  expect(withDateLike).toEqual(withDateLikeExpected)
  expect(withNumber).toEqual(withNumberExpected)
})

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

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

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

test('adds a nested key to a nested non-empty object - curry case 1', () => {
  expect(assocPath('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 - curry case 1', () => {
  expect(assocPath('b', 2)({ a : 1 })).toEqual({
    a : 1,
    b : 2,
  })
})

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

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

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

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

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

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

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

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

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

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

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

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

interface Output {
  a: number,
  foo: {bar: number},
}

describe('R.assocPath - user must explicitly set type of output', () => {
  it('with array as path input', () => {
    const result = assocPath<Output>(['foo', 'bar'], 2, {a: 1})

    result // $ExpectType Output
  })
  it('with string as path input', () => {
    const result = assocPath<Output>('foo.bar', 2, {a: 1})

    result // $ExpectType Output
  })
})

describe('R.assocPath - curried', () => {
  it('with array as path input', () => {
    const result = assocPath<Output>(['foo', 'bar'], 2)({a: 1})

    result // $ExpectType Output
  })
  it('with string as path input', () => {
    const result = assocPath<Output>('foo.bar', 2)({a: 1})

    result // $ExpectType Output
  })
})

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

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(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'

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')
})
Typescript test
import {both} from 'rambda'

describe('R.both', () => {
  it('with passed type', () => {
    const fn = both<number>(
      x => x > 1,
      x => x % 2 === 0
    )
    fn // $ExpectType Predicate<number>
    const result = fn(2) // $ExpectType boolean
    result // $ExpectType boolean
  })
  it('with passed type - curried', () => {
    const fn = both<number>(x => x > 1)(x => x % 2 === 0)
    fn // $ExpectType Predicate<number>
    const result = fn(2)
    result // $ExpectType boolean
  })
  it('no type passed', () => {
    const fn = both(
      x => {
        x // $ExpectType any
        return x > 1
      },
      x => {
        x // $ExpectType any
        return x % 2 === 0
      }
    )
    const result = fn(2)
    result // $ExpectType boolean
  })
  it('no type passed - curried', () => {
    const fn = both((x: number) => {
      x // $ExpectType number
      return x > 1
    })((x: number) => {
      x // $ExpectType number
      return x % 2 === 0
    })
    const result = fn(2)
    result // $ExpectType boolean
  })
})

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

chain

chain<T, U>(fn: (n: T) => readonly U[], list: readonly T[]): readonly 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) => readonly U[], list: readonly T[]): readonly U[];
chain<T, U>(fn: (n: T) => readonly U[]): (list: readonly T[]) => readonly U[];
chain<X0, X1, R>(fn: (x0: X0, x1: X1) => R, fn1: (x1: X1) => X0): (x1: X1) => R;
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 } from './chain'

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 ] ])
})
Typescript test
import {chain} from 'rambda'

const list = [1, 2, 3]
const fn = (x: number) => [`${x}`, `${x}`]

describe('R.chain', () => {
  it('without passing type', () => {
    const result = chain(fn, list)
    result // $ExpectType string[]

    const curriedResult = chain(fn)(list)
    curriedResult // $ExpectType string[]
  })
})

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

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'

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'

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

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

describe('R.clamp', () => {
  it('happy', () => {
    const result = clamp(1, 10, 20)
    result // $ExpectType number
  })
})

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

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.

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: readonly T[]): readonly T[];
R.clone source
import { _isArray } from './_internals/_isArray'

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 } from './clone'
import { equals } from './equals'

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()).toEqual(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 ])
})
Typescript test
import {clone} from 'rambda'

describe('R.clone', () => {
  it('happy', () => {
    const obj = {a: 1, b: 2}
    const result = clone(obj)
    result // $ExpectType { a: number; b: number; }
  })
})
Rambda is fastest. Ramda is 96.03% slower and Lodash is 91.75% slower
const R = require('../../dist/rambda.js')

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

const clone = [
  {
    label : 'Rambda',
    fn    : () => {
      R.clone(input)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.clone(input)
    },
  },
  {
    label : 'Lodash.cloneDeep',
    fn    : () => {
      _.cloneDeep(input)
    },
  },
]

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

complement

complement<T extends readonly any[]>(pred: (...args: T) => boolean): (...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 readonly any[]>(pred: (...args: T) => boolean): (...args: T) => boolean;
R.complement source
export function complement(fn){
  return (...input) => !fn(...input)
}
Tests
import { complement } from './complement'

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
  )).toEqual(false)
  expect(f(
    12, 2, 6
  )).toEqual(true)
})
Typescript test
import {complement, isNil} from 'rambda'

describe('R.complement', () => {
  it('happy', () => {
    const fn = complement(isNil)
    const result = fn(null)
    result // $ExpectType boolean
  })
})

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

compose

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

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

concat

concat<T>(x: readonly T[], y: readonly T[]): readonly 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: readonly T[], y: readonly T[]): readonly T[];
concat<T>(x: readonly T[]): (y: readonly T[]) => readonly 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'

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')).toEqual('ABCDEF')
})
Typescript test
import {concat} from 'rambda'

const list1 = [1, 2, 3]
const list2 = [4, 5, 6]

describe('R.concat', () => {
  it('happy', () => {
    const result = concat(list1, list2)

    result // $ExpectType number[]
  })
  it('curried', () => {
    const result = concat(list1)(list2)

    result // $ExpectType number[]
  })
})

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

cond

cond(conditions: readonly (readonly [Pred, (...a: readonly any[]) => any])[]): (...x: readonly any[]) => any

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(conditions: readonly (readonly [Pred, (...a: readonly any[]) => any])[]): (...x: readonly any[]) => any;
cond<A, B>(conditions: readonly (readonly [SafePred<A>, (...a: readonly A[]) => B])[]): (...x: readonly A[]) => B;
R.cond source
export function cond(conditions){
  return input => {
    let done = false
    let toReturn
    conditions.forEach(([ predicate, resultClosure ]) => {
      if (!done && predicate(input)){
        done = true
        toReturn = resultClosure(input)
      }
    })

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

test('returns a function', () => {
  expect(typeof cond([])).toEqual('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)).toEqual('water freezes at 0°C')
  expect(fn(50)).toEqual('nothing special happens at 50°C')
  expect(fn(100)).toEqual('water boils at 100°C')
})

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

test('predicates are tested in order', () => {
  const fn = cond([
    [ T, always('foo') ],
    [ T, always('bar') ],
    [ T, always('baz') ],
  ])
  expect(fn()).toEqual('foo')
})
Typescript test
import {cond, always, equals} from 'rambda'

describe('R.cond', () => {
  it('happy', () => {
    const fn = cond<number, string>([
      [equals(0), always('water freezes at 0°C')],
      [equals(100), always('water boils at 100°C')],
      [
        () => true,
        function(temp) {
          return 'nothing special happens at ' + temp + '°C'
        },
      ],
    ])

    const result = fn(0)
    result // $ExpectType string
  })
})

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

converge

converge(after: ((...a: readonly any[]) => any), fns: ReadonlyArray<((...x: readonly any[]) => any)>): (...y: readonly 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: readonly any[]) => any), fns: ReadonlyArray<((...x: readonly any[]) => any)>): (...y: readonly any[]) => any;
R.converge source
import { curryN } from './curryN'
import { map } from './map'
import { max } from './max'
import { reduce } from './reduce'

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'
import { converge } from './converge'
import { multiply } from './multiply'

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)).toEqual(161)
})

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

test('returns a function with the length of the longest argument', () => {
  expect(f1.length).toEqual(1)
  expect(f2.length).toEqual(2)
  expect(f3.length).toEqual(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)).toEqual(2)
  expect(b.call(context, 1)).toEqual(3)
  expect(d.call(context, 1)).toEqual(5)
})

test('works with empty functions list', () => {
  const fn = converge(function (){
    return arguments.length
  }, [])
  expect(fn.length).toEqual(0)
  expect(fn()).toEqual(0)
})
Typescript test
import {converge} from 'ramda'

const mult = (a: number, b: number) => {
  return a * b
}
const fn = converge(mult, [
  (a: number) => {
    return a
  },
  (a: number, b: number) => {
    return b
  },
])

describe('R.converge', () => {
  it('happy', () => {
    const result = fn(2, 3)
    const curriedResult = fn(2)(3)

    result // $ExpectType any
    curriedResult // $ExpectType any
  })
})
Rambda is slower than Ramda with 49.12%
const R = require('../../dist/rambda.js')

const converge = [
  {
    label : 'Rambda',
    fn    : () => {
      const fn = Ramda.converge(Ramda.multiply, [ Ramda.add(1), Ramda.add(3) ])

      fn(4)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      const fn = R.converge(R.multiply, [ R.add(1), R.add(3) ])

      fn(4)
    },
  },
]

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

curry

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

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

curryN

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

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

dec

It decrements a number.

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

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'

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

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

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

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

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

test('when inputArgument passes initial check', () => {
  expect(defaultTo('foo', 'bar')).toEqual('bar')
})
Typescript test
import {defaultTo} from 'rambda'

describe('R.defaultTo with Ramda spec', () => {
  it('happy', () => {
    const result = defaultTo('foo', '')
    result // $ExpectType "" | "foo"
  })
  it('with explicit type', () => {
    const result = defaultTo<string>('foo', null)
    result // $ExpectType string
  })
})
Rambda is faster than Ramda with 50.3%
const R = require('../../dist/rambda.js')

const input = [ null, undefined, 5 ]

const defaultTo = [
  {
    label : 'Rambda',
    fn    : () => {
      R.defaultTo(3, input[ 0 ])
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.defaultTo(3, input[ 0 ])
    },
  },
  {
    label : 'Rambda with multiple arguments',
    fn    : () => {
      R.defaultTo(3, ...input)
    },
  },
]

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

difference

difference<T>(a: readonly T[], b: readonly T[]): readonly 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 = difference(a, b)
// => [ 1, 2 ]

Try this R.difference example in Rambda REPL

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

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 } from './difference'

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([ NaN ], [ NaN ]).length).toEqual(0)
})
Typescript test
import {difference} from 'rambda'

const list1 = [1, 2, 3]
const list2 = [1, 2, 4]

describe('R.difference', () => {
  it('happy', () => {
    const result = difference(list1, list2)

    result // $ExpectType number[]
  })
  it('curried', () => {
    const result = difference(list1)(list2)

    result // $ExpectType number[]
  })
})

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

dissoc

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

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

divide

R.divide(71, 100) // => 0.71

Try this R.divide example in Rambda REPL

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

drop

drop<T>(howMany: number, input: readonly T[]): readonly 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: readonly T[]): readonly T[];
drop(howMany: number, input: string): string;
drop<T>(howMany: number): {
  <T>(input: readonly T[]): readonly 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'

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')).toEqual('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)
})
Typescript test
import {drop} from 'rambda'

const list = [1, 2, 3, 4]
const str = 'foobar'
const howMany = 2

describe('R.drop - array', () => {
  it('happy', () => {
    const result = drop(howMany, list)
    result // $ExpectType number[]
  })
  it('curried', () => {
    const result = drop(howMany)(list)
    result // $ExpectType number[]
  })
})

describe('R.drop - string', () => {
  it('happy', () => {
    const result = drop(howMany, str)
    result // $ExpectType string
  })
  it('curried', () => {
    const result = drop(howMany)(str)
    result // $ExpectType string
  })
})
Rambda is faster than Ramda with 97.45%
const R = require('../../dist/rambda.js')

const input = [ 1, 2, 3, 4 ]

const drop = [
  {
    label : 'Rambda',
    fn    : () => {
      R.drop(3, input)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.drop(3, input)
    },
  },
]

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

dropLast

dropLast<T>(howMany: number, input: readonly T[]): readonly 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: readonly T[]): readonly T[];
dropLast(howMany: number, input: string): string;
dropLast<T>(howMany: number): {
  <T>(input: readonly T[]): readonly 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'

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')).toEqual('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)
})
Typescript test
import {dropLast} from 'rambda'

const list = [1, 2, 3, 4]
const str = 'foobar'
const howMany = 2

describe('R.dropLast - array', () => {
  it('happy', () => {
    const result = dropLast(howMany, list)
    result // $ExpectType number[]
  })
  it('curried', () => {
    const result = dropLast(howMany)(list)
    result // $ExpectType number[]
  })
})

describe('R.dropLast - string', () => {
  it('happy', () => {
    const result = dropLast(howMany, str)
    result // $ExpectType string
  })
  it('curried', () => {
    const result = dropLast(howMany)(str)
    result // $ExpectType string
  })
})
Rambda is faster than Ramda with 97.07%
const R = require('../../dist/rambda.js')

const input = [ 1, 2, 3, 4 ]

const dropLast = [
  {
    label : 'Rambda',
    fn    : () => {
      R.dropLast(3, input)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.dropLast(3, input)
    },
  },
]

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

dropLastWhile

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

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

dropRepeats

dropRepeats<T>(list: readonly T[]): readonly 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: readonly T[]): readonly T[];
R.dropRepeats source
import { _isArray } from './_internals/_isArray'
import { equals } from './equals'

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'
import { add } from './add'
import { dropRepeats } from './dropRepeats'

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(`
        Object {
          "ERRORS_MESSAGE_MISMATCH": 0,
          "ERRORS_TYPE_MISMATCH": 0,
          "RESULTS_MISMATCH": 1,
          "SHOULD_NOT_THROW": 3,
          "SHOULD_THROW": 0,
        }
      `)
    },
    fn      : dropRepeats,
    fnRamda : dropRepeatsRamda,
  })
})
Typescript test
import {dropRepeats} from 'rambda'

describe('R.dropRepeats', () => {
  it('happy', () => {
    const result = dropRepeats([1, 2, 2, 3])

    result // $ExpectType number[]
  })
})

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

dropRepeatsWith

const list = [{a:1,b:2}, {a:1,b:3}, {a:2, b:4}]
const result = R.dropRepeatsWith(R.prop('a'))

// => [{a:1,b:2}, {a:2, b:4}]

Try this R.dropRepeatsWith example in Rambda REPL

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

dropWhile

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

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

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'

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()
})
Typescript test
import {either} from 'rambda'

describe('R.either', () => {
  it('with passed type', () => {
    const fn = either<number>(
      x => x > 1,
      x => x % 2 === 0
    )
    fn // $ExpectType Predicate<number>
    const result = fn(2) // $ExpectType boolean
    result // $ExpectType boolean
  })
  it('with passed type - curried', () => {
    const fn = either<number>(x => x > 1)(x => x % 2 === 0)
    fn // $ExpectType Predicate<number>
    const result = fn(2)
    result // $ExpectType boolean
  })
  it('no type passed', () => {
    const fn = either(
      x => {
        x // $ExpectType any
        return x > 1
      },
      x => {
        x // $ExpectType any
        return x % 2 === 0
      }
    )
    const result = fn(2)
    result // $ExpectType boolean
  })
  it('no type passed - curried', () => {
    const fn = either((x: number) => {
      x // $ExpectType number
      return x > 1
    })((x: number) => {
      x // $ExpectType number
      return x % 2 === 0
    })
    const result = fn(2)
    result // $ExpectType boolean
  })
})

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

endsWith

endsWith(target: string, str: string): boolean

Curried version of String.prototype.endsWith

💥 It doesn't work with arrays unlike its corresponding Ramda method.

const str = 'foo-bar'
const target = '-bar'

const result = R.endsWith(target, str)
// => true

Try this R.endsWith example in Rambda REPL

All Typescript definitions
endsWith(target: string, str: string): boolean;
endsWith(target: string): (str: string) => boolean;
R.endsWith source
export function endsWith(target, str){
  if (arguments.length === 1) return _str => endsWith(target, _str)

  return str.endsWith(target)
}
Tests
import { endsWith } from './endsWith'

test('happy', () => {
  expect(endsWith('bar', 'foo-bar')).toBeTrue()
  expect(endsWith('baz')('foo-bar')).toBeFalse()
})

test('does not work with arrays', () => {
  expect(() => endsWith([ 'c' ], [ 'a', 'b', 'c' ])).toThrowWithMessage(Error,
    'str.endsWith is not a function')
})
Typescript test
import {endsWith} from 'rambda'

const target = 'foo'
const input = 'foo bar'

describe('R.endsWith', () => {
  it('happy', () => {
    const result = endsWith(target, input)

    result // $ExpectType boolean
  })
  it('curried', () => {
    const result = endsWith(target)(input)

    result // $ExpectType boolean
  })
})

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

eqProps

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

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

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 { type } from './type'

function parseError(maybeError){
  const typeofError = maybeError.__proto__.toString()
  if (![ 'Error', 'TypeError' ].includes(typeofError)) return []

  return [ typeofError, maybeError.message ]
}

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)

  const aType = type(a)
  if (aType !== type(b)) return false
  if (aType === 'Function'){
    return a.name === undefined ? false : a.name === b.name
  }

  if ([ 'NaN', 'Undefined', 'Null' ].includes(aType)) return true

  if (aType === 'Number'){
    if (Object.is(-0, a) !== Object.is(-0, b)) return false

    return a.toString() === b.toString()
  }

  if ([ 'String', 'Boolean' ].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

  const aError = parseError(a)
  const bError = parseError(b)

  if (aError[ 0 ]){
    return bError[ 0 ] ?
      aError[ 0 ] === bError[ 0 ] && aError[ 1 ] === bError[ 1 ] :
      false
  }

  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 } from './equals'

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/)).toEqual(true)
  expect(equals(/s/, /d/)).toEqual(false)
  expect(equals(/a/gi, /a/gi)).toEqual(true)
  expect(equals(/a/gim, /a/gim)).toEqual(true)
  expect(equals(/a/gi, /a/i)).toEqual(false)
})

test('not a number', () => {
  expect(equals([ NaN ], [ NaN ])).toBeTrue()
})

test('new number', () => {
  expect(equals(new Number(0), new Number(0))).toEqual(true)
  expect(equals(new Number(0), new Number(1))).toEqual(false)
  expect(equals(new Number(1), new Number(0))).toEqual(false)
})

test('new string', () => {
  expect(equals(new String(''), new String(''))).toEqual(true)
  expect(equals(new String(''), new String('x'))).toEqual(false)
  expect(equals(new String('x'), new String(''))).toEqual(false)
  expect(equals(new String('foo'), new String('foo'))).toEqual(true)
  expect(equals(new String('foo'), new String('bar'))).toEqual(false)
  expect(equals(new String('bar'), new String('foo'))).toEqual(false)
})

test('new Boolean', () => {
  expect(equals(new Boolean(true), new Boolean(true))).toEqual(true)
  expect(equals(new Boolean(false), new Boolean(false))).toEqual(true)
  expect(equals(new Boolean(true), new Boolean(false))).toEqual(false)
  expect(equals(new Boolean(false), new Boolean(true))).toEqual(false)
})

test('new Error', () => {
  expect(equals(new Error('XXX'), {})).toEqual(false)
  expect(equals(new Error('XXX'), new TypeError('XXX'))).toEqual(false)
  expect(equals(new Error('XXX'), new Error('YYY'))).toEqual(false)
  expect(equals(new Error('XXX'), new Error('XXX'))).toEqual(true)
  expect(equals(new Error('XXX'), new TypeError('YYY'))).toEqual(false)
})

test('with dates', () => {
  expect(equals(new Date(0), new Date(0))).toEqual(true)
  expect(equals(new Date(1), new Date(1))).toEqual(true)
  expect(equals(new Date(0), new Date(1))).toEqual(false)
  expect(equals(new Date(1), new Date(0))).toEqual(false)
  expect(equals(new Date(0), {})).toEqual(false)
  expect(equals({}, new Date(0))).toEqual(false)
})

test('ramda spec', () => {
  expect(equals({}, {})).toEqual(true)

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

  expect(equals({
    a : 2,
    b : 3,
  },
  {
    b : 3,
    a : 2,
  })).toEqual(true)

  expect(equals({
    a : 2,
    b : 3,
  },
  {
    a : 3,
    b : 3,
  })).toEqual(false)

  expect(equals({
    a : 2,
    b : 3,
    c : 1,
  },
  {
    a : 2,
    b : 3,
  })).toEqual(false)
})

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('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,
  },
  {
    b : 2,
    a : 1,
  })).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,
  },
  {
    b : 2,
    a : 1,
    c : 3,
  })).toBeFalse()

  expect(equals({
    x : {
      a : 1,
      b : 2,
    },
  },
  {
    x : {
      b : 2,
      a : 1,
      c : 3,
    },
  })).toBeFalse()

  expect(equals({
    a : 1,
    b : 2,
  },
  {
    b : 3,
    a : 1,
  })).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()
})
Typescript test
import {equals} from 'rambda'

describe('R.equals', () => {
  it('happy', () => {
    const result = equals(4, 1)
    result // $ExpectType boolean
  })
  it('with object', () => {
    const foo = {a: 1}
    const bar = {a: 2}
    const result = equals(foo, bar)
    result // $ExpectType boolean
  })
  it('curried', () => {
    const result = equals(4)(1)

    result // $ExpectType boolean
  })
})
Lodash is fastest. Rambda is 72.11% slower and Ramda is 79.48% slower
const R = require('../../dist/rambda.js')

const a = { a : { b : { c : 1 } } }
const b = { a : { b : { c : 1 } } }

const equals = [
  {
    label : 'Rambda',
    fn    : () => {
      R.equals(a, b)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.equals(a, b)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.isEqual(a, b)
    },
  },
]

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

evolve

evolve<T, U>(rules: ReadonlyArray<(x: T) => U>, list: readonly T[]): readonly 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: ReadonlyArray<(x: T) => U>, list: readonly T[]): readonly U[];
evolve<T, U>(rules: ReadonlyArray<(x: T) => U>) : (list: readonly T[]) => readonly 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'
import { mapArray, mapObject } from './map'
import { type } from './type'

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'
import { compareCombinations, compareToRamda } from './_internals/testUtils'
import { evolve } from './evolve'

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(`
        Object {
          "ERRORS_MESSAGE_MISMATCH": 0,
          "ERRORS_TYPE_MISMATCH": 4,
          "RESULTS_MISMATCH": 0,
          "SHOULD_NOT_THROW": 51,
          "SHOULD_THROW": 0,
        }
      `)
    },
    secondInput : possibleIterables,
    fn          : evolve,
    fnRamda     : evolveRamda,
  })
})
Typescript test
import {evolve, add} from 'rambda'

describe('R.evolve', () => {
  it('happy', () => {
    const input = {
      foo: 2,
      nested: {
        a: 1,
        bar: 3,
      },
    }
    const rules = {
      foo: add(1),
      nested: {
        a: add(-1),
        bar: add(1),
      },
    }
    const result = evolve(rules, input)
    const curriedResult = evolve(rules)(input)

    result.nested.a // $ExpectType number
    curriedResult.nested.a // $ExpectType number
    result.nested.bar // $ExpectType number
    result.foo // $ExpectType number
  })
  it('with array', () => {
    const rules = [String, String]
    const input = [100, 1400]
    const result = evolve(rules, input)
    const curriedResult = evolve(rules)(input)
    result // $ExpectType string[]
    curriedResult // $ExpectType string[]
  })
})

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

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: readonly T[]) => readonly 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: readonly T[]) => readonly T[];
filter<T>(predicate: Predicate<T>, input: readonly T[]): readonly 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'

export function filterObject(fn, obj){
  const willReturn = {}

  for (const prop in obj){
    if (fn(
      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) return []
  if (_isArray(iterable)) return filterArray(predicate, iterable)

  return filterObject(predicate, iterable)
}
Tests
import Ramda from 'ramda'

import { F } from './F'
import { filter } from './filter'
import { T } from './T'

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('bad inputs difference between Ramda and Rambda', () => {
  expect(filter(T)(undefined)).toEqual([])
  expect(filter(F, null)).toEqual([])
  expect(() => Ramda.filter(T, null)).toThrowWithMessage(TypeError,
    'Cannot read property \'filter\' of null')
  expect(() => Ramda.filter(T, undefined)).toThrowWithMessage(TypeError,
    'Cannot read property \'filter\' of undefined')
})

test('predicate when input is object', () => {
  const obj = {
    a : 1,
    b : 2,
  }
  const predicate = (
    val, prop, inputObject
  ) => {
    expect(inputObject).toEqual(obj)
    expect(typeof prop).toEqual('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)
})
Typescript test
import {filter} from 'rambda'

const list = [1, 2, 3]
const obj = {a: 1, b: 2}

describe('R.filter with array', () => {
  it('happy', () => {
    const result = filter<number>(x => {
      x // $ExpectType number
      return x > 1
    }, list)
    result // $ExpectType number[]
  })
  it('curried', () => {
    const result = filter<number>(x => {
      x // $ExpectType number
      return x > 1
    })(list)
    result // $ExpectType number[]
  })
})

describe('R.filter with objects', () => {
  it('happy', () => {
    const result = filter<number>((val, prop, origin) => {
      val // $ExpectType number
      prop // $ExpectType string
      origin // $ExpectType Dictionary<number>

      return val > 1
    }, obj)
    result // $ExpectType Dictionary<number>
  })
  it('curried version requires second dummy type', () => {
    const result = filter<number, any>((val, prop, origin) => {
      val // $ExpectType number
      prop // $ExpectType string
      origin // $ExpectType Dictionary<number>

      return val > 1
    })(obj)
    result // $ExpectType Dictionary<number>
  })
})
Rambda is fastest. Ramda is 94.74% slower and Lodash is 58.18% slower
const R = require('../../dist/rambda.js')

const arr = [ 1, 2, 3, 4 ]
const fn = x => x > 2
const filter = [
  {
    label : 'Rambda',
    fn    : () => {
      R.filter(fn, arr)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.filter(fn, arr)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.filter(arr, fn)
    },
  },
]

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

find

find<T>(predicate: (x: T) => boolean, list: readonly 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: readonly T[]): T | undefined;
find<T>(predicate: (x: T) => boolean): (list: readonly 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'
import { propEq } from './propEq'

const list = [ { a : 1 }, { a : 2 }, { a : 3 } ]

test('happy', () => {
  const fn = propEq('a', 2)
  expect(find(fn, list)).toEqual({ a : 2 })
})

test('with curry', () => {
  const fn = propEq('a', 4)
  expect(find(fn)(list)).toBeUndefined()
})

test('with empty list', () => {
  expect(find(() => true, [])).toBeUndefined()
})
Typescript test
import {find} from 'rambda'

const list = [1, 2, 3]

describe('R.find', () => {
  it('happy', () => {
    const predicate = (x: number) => x > 2
    const result = find(predicate, list)
    result // $ExpectType number | undefined
  })
  it('curried', () => {
    const predicate = (x: number) => x > 2
    const result = find(predicate)(list)
    result // $ExpectType number | undefined
  })
})
Rambda is fastest. Ramda is 98.2% slower and Lodash is 88.96% slower
const R = require('../../dist/rambda.js')

const fn = x => x > 2
const list = [ 1, 2, 3, 4 ]

const find = [
  {
    label : 'Rambda',
    fn    : () => {
      R.find(fn, list)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.find(fn, list)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.find(list, fn)
    },
  },
]

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

findIndex

findIndex<T>(predicate: (x: T) => boolean, list: readonly 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: readonly T[]): number;
findIndex<T>(predicate: (x: T) => boolean): (list: readonly 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'
import { propEq } from './propEq'

const list = [ { a : 1 }, { a : 2 }, { a : 3 } ]

test('happy', () => {
  expect(findIndex(propEq('a', 2), list)).toEqual(1)

  expect(findIndex(propEq('a', 1))(list)).toEqual(0)

  expect(findIndex(propEq('a', 4))(list)).toEqual(-1)
})
Typescript test
import {findIndex} from 'rambda'

const list = [1, 2, 3]

describe('R.findIndex', () => {
  it('happy', () => {
    const predicate = (x: number) => x > 2
    const result = findIndex(predicate, list)
    result // $ExpectType number
  })
  it('curried', () => {
    const predicate = (x: number) => x > 2
    const result = findIndex(predicate)(list)
    result // $ExpectType number
  })
})
Rambda is fastest. Ramda is 97.97% slower and Lodash is 79.39% slower
const R = require('../../dist/rambda.js')

const fn = x => x > 2
const list = [ 1, 2, 3, 4 ]

const findIndex = [
  {
    label : 'Rambda',
    fn    : () => {
      R.findIndex(fn, list)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.findIndex(fn, list)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.findIndex(list, fn)
    },
  },
]

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

findLast

findLast<T>(fn: (x: T) => boolean, list: readonly 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: readonly T[]): T | undefined;
findLast<T>(fn: (x: T) => boolean): (list: readonly 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'

test('happy', () => {
  const result = findLast(x => x > 1,
    [ 1, 1, 1, 2, 3, 4, 1 ])
  expect(result).toEqual(4)

  expect(findLast(x => x === 0, [ 0, 1, 1, 2, 3, 4, 1 ])).toEqual(0)
})

test('with curry', () => {
  expect(findLast(x => x > 1)([ 1, 1, 1, 2, 3, 4, 1 ])).toEqual(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)).toEqual(0)
  expect(findLast(gt100, a)).toEqual(300)
  expect(findLast(isStr, a)).toEqual('cow')
  expect(findLast(xGt100, a)).toEqual(obj2)
})

test('ramda 2', () => {
  expect(findLast(even, [ 'zing' ])).toEqual(undefined)
})

test('ramda 3', () => {
  expect(findLast(even, [ 2, 3, 5 ])).toEqual(2)
})

test('ramda 4', () => {
  expect(findLast(even, [])).toEqual(undefined)
})
Typescript test
import {findLast} from 'rambda'

const list = [1, 2, 3]

describe('R.findLast', () => {
  it('happy', () => {
    const predicate = (x: number) => x > 2
    const result = findLast(predicate, list)
    result // $ExpectType number | undefined
  })
  it('curried', () => {
    const predicate = (x: number) => x > 2
    const result = findLast(predicate)(list)
    result // $ExpectType number | undefined
  })
})

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

findLastIndex

findLastIndex<T>(predicate: (x: T) => boolean, list: readonly 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: readonly T[]): number;
findLastIndex<T>(predicate: (x: T) => boolean): (list: readonly 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'

test('happy', () => {
  const result = findLastIndex(x => x > 1,
    [ 1, 1, 1, 2, 3, 4, 1 ])

  expect(result).toEqual(5)

  expect(findLastIndex(x => x === 0, [ 0, 1, 1, 2, 3, 4, 1 ])).toEqual(0)
})

test('with curry', () => {
  expect(findLastIndex(x => x > 1)([ 1, 1, 1, 2, 3, 4, 1 ])).toEqual(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)).toEqual(15)
  expect(findLastIndex(gt100, a)).toEqual(9)
  expect(findLastIndex(isStr, a)).toEqual(3)
  expect(findLastIndex(xGt100, a)).toEqual(10)
})

test('ramda 2', () => {
  expect(findLastIndex(even, [ 'zing' ])).toEqual(-1)
})

test('ramda 3', () => {
  expect(findLastIndex(even, [ 2, 3, 5 ])).toEqual(0)
})

test('ramda 4', () => {
  expect(findLastIndex(even, [])).toEqual(-1)
})
Typescript test
import {findLastIndex} from 'rambda'

const list = [1, 2, 3]

describe('R.findLastIndex', () => {
  it('happy', () => {
    const predicate = (x: number) => x > 2
    const result = findLastIndex(predicate, list)
    result // $ExpectType number
  })
  it('curried', () => {
    const predicate = (x: number) => x > 2
    const result = findLastIndex(predicate)(list)
    result // $ExpectType number
  })
})

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

flatten

flatten<T>(list: readonly any[]): readonly 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: readonly any[]): readonly T[];
R.flatten source
import { _isArray } from './_internals/_isArray'

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'

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 ])
})
Typescript test
import {flatten} from 'rambda'

describe('flatten', () => {
  it('happy', () => {
    const result = flatten<number>([1, 2, [3, [4]]])
    result // $ExpectType number[]
  })
})
Lodash is fastest. Rambda is 6.56% slower and Ramda is 95.38% slower
const R = require('../../dist/rambda.js')

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

const flatten = [
  {
    label : 'Rambda',
    fn    : () => {
      R.flatten(list)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.flatten(list)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.flatten(list)
    },
  },
]

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

flip

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

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

forEach

forEach<T>(fn: Iterator<T, void>, list: readonly T[]): readonly 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: readonly T[]): readonly T[];
forEach<T>(fn: Iterator<T, void>): (list: readonly T[]) => readonly 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'
import { _keys } from './_internals/_keys'

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

  if (list === undefined){
    return
  }

  if (_isArray(list)){
    let index = 0
    const len = list.length

    while (index < len){
      fn(list[ index ])
      index++
    }
  } else {
    let index = 0
    const keys = _keys(list)
    const len = keys.length

    while (index < len){
      const key = keys[ index ]
      fn(
        list[ key ], key, list
      )
      index++
    }
  }

  return list
}
Tests
import { forEach } from './forEach'
import { type } from './type'

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)
})
Typescript test
import {forEach} from 'rambda'

const list = [1, 2, 3]
const obj = {a: 1, b: 2}

describe('R.forEach with arrays', () => {
  it('happy', () => {
    const result = forEach(a => {
      a // $ExpectType number
    }, list)
    result // $ExpectType number[]
  })
  it('curried require an explicit typing', () => {
    const result = forEach<number>(a => {
      a // $ExpectType number
    })(list)
    result // $ExpectType number[]
  })
})

describe('R.forEach with objects', () => {
  it('happy', () => {
    const result = forEach((a, b, c) => {
      a // $ExpectType number
      b // $ExpectType string
      c // $ExpectType Dictionary<number>
      return `${a}`
    }, obj)
    result // $ExpectType Dictionary<number>
  })
  it('curried require an input typing and a dummy third typing', () => {
    // Required in order all typings to work
    const result = forEach<number, any>((a, b, c) => {
      a // $ExpectType number
      b // $ExpectType string
      c // $ExpectType Dictionary<number>
    })(obj)
    result // $ExpectType Dictionary<number>
  })
  it('iterator without property', () => {
    const result = forEach(a => {
      a // $ExpectType number
    }, obj)
    result // $ExpectType Dictionary<number>
  })
})

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

fromPairs

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

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

groupBy

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

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

groupWith

groupWith<T>(compareFn: (x: T, y: T) => boolean): (input: readonly T[]) => readonly (readonly T[])[]

It returns separated version of list or string input, where separation is done with equality compareFn function.

const compareFn = (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: readonly T[]) => readonly (readonly T[])[];
groupWith<T>(compareFn: (x: T, y: T) => boolean, input: readonly T[]): readonly (readonly T[])[];
groupWith<T>(compareFn: (x: T, y: T) => boolean, input: string): readonly string[];
R.groupWith source
import { _isArray } from './_internals/_isArray'

export function groupWith(compareFn, list){
  if (!_isArray(list)) throw new TypeError('list.reduce is not a function')

  const clone = list.slice()

  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'
import { groupWith } from './groupWith'

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')).toThrowWithMessage(TypeError,
    '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)
})
Typescript test
import {groupWith} from 'rambda'

describe('R.groupWith', () => {
  it('happy', () => {
    const groupWithFn = (x: string, y: string) => x.length === y.length
    const list = ['foo', 'bar', 'bazzz']

    const result = groupWith(groupWithFn, list)
    const curriedResult = groupWith(groupWithFn)(list)
    result // $ExpectType (string[])[]
    curriedResult // $ExpectType (string[])[]
  })
})

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

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', obj),
  R.has('b', obj)
]
// => [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[ prop ] !== undefined
}
Tests
import { has } from './has'

test('happy', () => {
  expect(has('a')({ a : 1 })).toBeTrue()
  expect(has('b', { a : 1 })).toBeFalse()
})

test('with non-object', () => {
  expect(has('a', undefined)).toEqual(false)
  expect(has('a', null)).toEqual(false)
  expect(has('a', true)).toEqual(false)
  expect(has('a', '')).toEqual(false)
  expect(has('a', /a/)).toEqual(false)
})
Typescript test
import {has} from 'rambda'

describe('R.has', () => {
  it('happy', () => {
    const result = has('foo', {a: 1})
    const curriedResult = has('bar')({a: 1})
    result // $ExpectType boolean
    curriedResult // $ExpectType boolean
  })
})

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

hasPath

hasPath<T>(
  path: string | readonly 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, obj),
  R.hasPath(pathAsArray, obj),
  R.hasPath('a.c', obj),
]
// => [true, true, false]

Try this R.hasPath example in Rambda REPL

All Typescript definitions
hasPath<T>(
  path: string | readonly string[],
  input: object
): boolean;
hasPath<T>(
  path: string | readonly string[]
): (input: object) => boolean;
R.hasPath source
import { path } from './path'

export function hasPath(maybePath, obj){
  if (arguments.length === 1){
    return objHolder => hasPath(maybePath, objHolder)
  }

  return path(maybePath, obj) !== undefined
}
Tests
import { hasPath } from './hasPath'

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)
})
Typescript test
import {hasPath} from 'rambda'

describe('R.hasPath', () => {
  it('string path', () => {
    const obj = {a: {b: 1}}
    const result = hasPath('a.b', obj)
    const curriedResult = hasPath('a.c')(obj)
    result // $ExpectType boolean
    curriedResult // $ExpectType boolean
  })
  it('array path', () => {
    const obj = {a: {b: 1}}
    const result = hasPath(['a', 'b'], obj)
    const curriedResult = hasPath(['a', 'c'])(obj)
    result // $ExpectType boolean
    curriedResult // $ExpectType boolean
  })
})

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

head

head<T>(input: readonly T[]): T | undefined

It returns the first element of list or string input.

const result = [
  R.head([1, 2, 3]),
  R.head('foo') 
]
// => [1, 'f']

Try this R.head example in Rambda REPL

All Typescript definitions
head<T>(input: readonly T[]): T | undefined;
head(input: string): string;
R.head source
export function head(listOrString){
  if (typeof listOrString === 'string') return listOrString[ 0 ] || ''

  return listOrString[ 0 ]
}
Tests
import { head } from './head'

test('head', () => {
  expect(head([ 'fi', 'fo', 'fum' ])).toEqual('fi')
  expect(head([])).toEqual(undefined)
  expect(head('foo')).toEqual('f')
  expect(head('')).toEqual('')
})
Typescript test
import {head} from 'rambda'

describe('R.head', () => {
  it('string', () => {
    const result = head('foo')
    result // $ExpectType string
  })
  it('array', () => {
    const result = head([1, 2, 3])
    result // $ExpectType number | undefined
  })
})

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

identical

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 obj = {a: 1};
R.identical(obj, obj); // => true
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

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

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(input){
  return input
}
Tests
import { identity } from './identity'

test('happy', () => {
  expect(identity(7)).toEqual(7)
  expect(identity(true)).toEqual(true)
  expect(identity({ a : 1 })).toEqual({ a : 1 })
})
Typescript test
import {identity} from 'rambda'

describe('R.identity', () => {
  it('happy', () => {
    const result = identity(4)
    result // $ExpectType 4
  })
})

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

ifElse

ifElse<T, U>(
  condition: (x: T) => boolean, 
  onTrue: (x: T) => U, 
  onFalse: (x: T) => U, 
): (x: T) => U

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, U>(
  condition: (x: T) => boolean, 
  onTrue: (x: T) => U, 
  onFalse: (x: T) => U, 
): (x: T) => U;
ifElse<T, K, U>(
  condition: (x: T, y: K) => boolean, 
  onTrue: (x: T, y: K) => U, 
  onFalse: (x: T, y: K) => U, 
): (x: T, y: K) => U;
R.ifElse source
import { curry } from './curry'

function ifElseFn(
  condition, onTrue, onFalse
){
  return (...input) => {
    const conditionResult =
      typeof condition === 'boolean' ? condition : condition(...input)

    if (conditionResult === true){
      return onTrue(...input)
    }

    return onFalse(...input)
  }
}

export const ifElse = curry(ifElseFn)
Tests
import { always } from './always'
import { has } from './has'
import { identity } from './identity'
import { ifElse } from './ifElse'
import { prop } from './prop'

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' })).toEqual(3)
  expect(fn({ fo : 'bar' })).toEqual(false)
})

test('ramda spec', () => {
  const ifIsNumber = ifElse(v)
  expect(ifIsNumber(t, identity)(15)).toEqual(16)
  expect(ifIsNumber(t, identity)('hello')).toEqual('hello')
})

test('pass all arguments', () => {
  const identity = function (a){
    return a
  }
  const v = function (){
    return true
  }
  const onTrue = function (a, b){
    expect(a).toEqual(123)
    expect(b).toEqual('abc')
  }
  ifElse(
    v, onTrue, identity
  )(123, 'abc')
})

test('accept constant as condition', () => {
  const fn = ifElse(true)(always(true))(always(false))

  expect(fn()).toEqual(true)
})

test('accept constant as condition - case 2', () => {
  const fn = ifElse(
    false, always(true), always(false)
  )

  expect(fn()).toEqual(false)
})

test('curry 1', () => {
  const fn = ifElse(condition, ifFn)(elseFn)

  expect(fn({ foo : 'bar' })).toEqual(3)
  expect(fn({ fo : 'bar' })).toEqual(false)
})

test('curry 2', () => {
  const fn = ifElse(condition)(ifFn)(elseFn)

  expect(fn({ foo : 'bar' })).toEqual(3)
  expect(fn({ fo : 'bar' })).toEqual(false)
})

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)
})
Typescript test
import {ifElse} from 'rambda'

describe('R.ifElse', () => {
  it('happy', () => {
    const condition = (x: number) => x > 5
    const onTrue = (x: number) => `foo${x}`
    const onFalse = (x: number) => `bar${x}`
    const fn = ifElse(condition, onTrue, onFalse)
    fn // $ExpectType (x: number) => string
    const result = fn(3)
    result // $ExpectType string
  })
  it('arity of 2', () => {
    const condition = (x: number, y: string) => x + y.length > 5
    const onTrue = (x: number, y: string) => `foo${x}-${y}`
    const onFalse = (x: number, y: string) => `bar${x}-${y}`
    const fn = ifElse(condition, onTrue, onFalse)
    fn // $ExpectType (x: number, y: string) => string
    const result = fn(3, 'hello')
    result // $ExpectType string
  })
})
Rambda is faster than Ramda with 70.97%
const R = require('../../dist/rambda.js')

const condition = R.has('foo')
const v = function (a){
  return typeof a === 'number'
}
const t = function (a){
  return a + 1
}
const ifFn = x => R.prop('foo', x).length
const elseFn = () => false

const ifElse = [
  {
    label : 'Rambda',
    fn    : () => {
      const fn = R.ifElse(condition, ifFn)(elseFn)

      fn({ foo : 'bar' })
      fn({ fo : 'bar' })

      const ifIsNumber = R.ifElse(v)
      ifIsNumber(t, R.identity)(15)
      ifIsNumber(t, R.identity)('hello')
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      const fn = Ramda.ifElse(condition, ifFn)(elseFn)

      fn({ foo : 'bar' })
      fn({ fo : 'bar' })

      const ifIsNumber = Ramda.ifElse(v)
      ifIsNumber(t, R.identity)(15)
      ifIsNumber(t, R.identity)('hello')
    },
  },
]

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

inc

It increments a number.

R.inc(1) // => 2

Try this R.inc example in Rambda REPL

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

includes

includes(valueToFind: string, input: readonly string[] | 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(valueToFind: string, input: readonly string[] | string): boolean;
includes(valueToFind: string): (input: readonly string[] | string) => boolean;
includes<T>(valueToFind: T, input: readonly T[]): boolean;
includes<T>(valueToFind: T): (input: readonly T[]) => boolean;
R.includes source
import { _isArray } from './_internals/_isArray'
import { equals } from './equals'

export function includesArray(valueToFind, input){
  let index = -1

  while (++index < input.length){
    if (equals(input[ index ], valueToFind)){
      return true
    }
  }

  return false
}

export function includes(valueToFind, input){
  if (arguments.length === 1) return _input => includes(valueToFind, _input)
  if (typeof input === 'string'){
    return input.includes(valueToFind)
  }
  if (!input){
    throw new TypeError(`Cannot read property \'indexOf\' of ${ input }`)
  }
  if (!_isArray(input)) return false

  return includesArray(valueToFind, input)
}
Tests
import R from 'ramda'

import { includes } from './includes'

test('includes with string', () => {
  const str = 'foo bar'

  expect(includes('bar')(str)).toBeTrue()
  expect(R.includes('bar')(str)).toBeTrue()
  expect(includes('never', str)).toBeFalse()
  expect(R.includes('never', str)).toBeFalse()
})

test('includes with array', () => {
  const arr = [ 1, 2, 3 ]

  expect(includes(2)(arr)).toBeTrue()
  expect(R.includes(2)(arr)).toBeTrue()

  expect(includes(4, arr)).toBeFalse()
  expect(R.includes(4, arr)).toBeFalse()
})

test('with wrong input that does not throw', () => {
  const result = includes(1, /foo/g)
  const ramdaResult = R.includes(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(() => R.includes(2, null)).toThrowWithMessage(TypeError,
    'Cannot read property \'indexOf\' of null')
  expect(() => includes(2, undefined)).toThrowWithMessage(TypeError,
    'Cannot read property \'indexOf\' of undefined')
  expect(() => R.includes(2, undefined)).toThrowWithMessage(TypeError,
    'Cannot read property \'indexOf\' of undefined')
})
Typescript test
import {includes} from 'rambda'

const list = [{a: {b: '1'}}, {a: {c: '2'}}, {a: {b: '3'}}]

describe('R.includes', () => {
  it('happy', () => {
    const result = includes({a: {b: '1'}}, list)
    result // $ExpectType boolean
  })
  it('with string', () => {
    const result = includes('oo', 'foo')
    const curriedResult = includes('oo')('foo')

    result // $ExpectType boolean
    curriedResult // $ExpectType boolean
  })
})
Rambda is faster than Ramda with 71.7%
const R = require('../../dist/rambda.js')

const str = 'more is less'

const includes = [
  {
    label : 'Rambda',
    fn    : () => {
      R.includes('less')(str)
      R.includes('more', str)
      R.includes('foo', str)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.includes('less')(str)
      Ramda.includes('more', str)
      Ramda.includes('foo', str)
    },
  },
]

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

indexBy

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

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

indexOf

It returns the index of the first element of list equals to valueToFind.

If there is no such element, it returns -1.

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

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

init

init<T>(input: readonly T[]): readonly 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>(input: readonly T[]): readonly T[];
init(input: string): string;
R.init source
import baseSlice from './_internals/baseSlice'

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'

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')).toEqual('fo')
  expect(init('f')).toEqual('')
  expect(init('')).toEqual('')
})
Typescript test
import {init} from 'rambda'

describe('R.init', () => {
  it('with string', () => {
    const result = init('foo')

    result // $ExpectType string
  })
  it('with list', () => {
    const result = init([1, 2, 3])

    result // $ExpectType number[]
  })
})
Lodash is fastest. Rambda is 94.42% slower and Ramda is 97.55% slower
const R = require('../../dist/rambda.js')

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

const init = [
  {
    label : 'Rambda',
    fn    : () => {
      R.init(list)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.init(list)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.initial(list)
    },
  },
]

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

intersection

It loops throw listA and listB and returns the intersection of the two according to R.equals.

const listA = [ { id : 1 }, { id : 2 }, { id : 3 }, { id : 4 } ]
const listB = [ { id : 3 }, { id : 4 }, { id : 5 }, { id : 6 } ]

const result = intersection(listA, listB)
// => [{ id : 3 }, { id : 4 }]

Try this R.intersection example in Rambda REPL

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

intersperse

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

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

is

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

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

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'

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'

test('happy', () => {
  expect(isEmpty(undefined)).toEqual(false)
  expect(isEmpty('')).toEqual(true)
  expect(isEmpty(null)).toEqual(false)
  expect(isEmpty(' ')).toEqual(false)
  expect(isEmpty(new RegExp(''))).toEqual(false)
  expect(isEmpty([])).toEqual(true)
  expect(isEmpty([ [] ])).toEqual(false)
  expect(isEmpty({})).toEqual(true)
  expect(isEmpty({ x : 0 })).toEqual(false)
  expect(isEmpty(0)).toEqual(false)
  expect(isEmpty(NaN)).toEqual(false)
  expect(isEmpty([ '' ])).toEqual(false)
})
Typescript test
import {isEmpty} from 'rambda'

describe('R.isEmpty', () => {
  it('happy', () => {
    const result = isEmpty('foo')
    result // $ExpectType boolean
  })
})
Lodash is fastest. Rambda is 51.68% slower and Ramda is 93.82% slower
const R = require('../../dist/rambda.js')

const isEmpty = [
  {
    label : 'Rambda',
    fn    : () => {
      R.isEmpty(undefined)
      R.isEmpty('')
      R.isEmpty(null)
      R.isEmpty(' ')
      R.isEmpty(new RegExp(''))
      R.isEmpty([])
      R.isEmpty([ [] ])
      R.isEmpty({})
      R.isEmpty({ x : 0 })
      R.isEmpty(0)
      R.isEmpty(NaN)
      R.isEmpty([ '' ])
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.isEmpty(undefined)
      Ramda.isEmpty('')
      Ramda.isEmpty(null)
      Ramda.isEmpty(' ')
      Ramda.isEmpty(new RegExp(''))
      Ramda.isEmpty([])
      Ramda.isEmpty([ [] ])
      Ramda.isEmpty({})
      Ramda.isEmpty({ x : 0 })
      Ramda.isEmpty(0)
      Ramda.isEmpty(NaN)
      Ramda.isEmpty([ '' ])
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.isEmpty(undefined)
      _.isEmpty('')
      _.isEmpty(null)
      _.isEmpty(' ')
      _.isEmpty(new RegExp(''))
      _.isEmpty([])
      _.isEmpty([ [] ])
      _.isEmpty({})
      _.isEmpty({ x : 0 })
      _.isEmpty(0)
      _.isEmpty(NaN)
      _.isEmpty([ '' ])
    },
  },
]

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

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'

test('happy', () => {
  expect(isNil(null)).toBeTrue()

  expect(isNil(undefined)).toBeTrue()

  expect(isNil([])).toBeFalse()
})

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

join

join<T>(glue: string, list: readonly 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: readonly T[]): string;
join<T>(glue: string): (list: readonly 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'

test('curry', () => {
  expect(join('|')([ 'foo', 'bar', 'baz' ])).toEqual('foo|bar|baz')

  expect(join('|', [ 1, 2, 3 ])).toEqual('1|2|3')

  const spacer = join(' ')

  expect(spacer([ 'a', 2, 3.4 ])).toEqual('a 2 3.4')
})
Typescript test
import {join} from 'rambda'

describe('R.join', () => {
  it('happy', () => {
    const result = join('|', [1, 2, 3])
    result // $ExpectType string
  })
})

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

keys

keys<T extends object>(x: T): readonly (keyof T)[]

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): readonly (keyof T)[];
keys<T>(x: T): readonly string[];
R.keys source
export function keys(x){
  return Object.keys(x)
}
Tests
import { keys } from './keys'

test('happy', () => {
  expect(keys({ a : 1 })).toEqual([ 'a' ])
})
Typescript test
import {keys} from 'rambda'

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

describe('R.keys', () => {
  it('happy', () => {
    const result = keys(obj)
    result // $ExpectType ("b" | "a")[]
  })
})

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

last

last(str: string): string

It returns the last element of input, as the input can be either a string or an array.

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: string): string;
last(emptyList: readonly []): undefined;
last<T extends any>(list: readonly T[]): T;
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'

test('with list', () => {
  expect(last([ 1, 2, 3 ])).toBe(3)
  expect(last([])).toBeUndefined()
})

test('with string', () => {
  expect(last('abc')).toEqual('c')
  expect(last('')).toEqual('')
})
Typescript test
import {last} from 'rambda'

describe('R.last', () => {
  it('string', () => {
    const result = last('foo')
    result // $ExpectType string
  })

  it('array', () => {
    const result = last([1, 2, 3])
    result // $ExpectType number
  })

  it('empty array', () => {
    const result = last([])
    result // $ExpectType undefined
  })
})
Rambda is fastest. Ramda is 99.64% slower and Lodash is 1.05% slower
const R = require('../../dist/rambda.js')

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

const last = [
  {
    label : 'Rambda',
    fn    : () => {
      R.last(list)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.last(list)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.last(list)
    },
  },
]

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

lastIndexOf

lastIndexOf<T>(target: T, list: readonly 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: readonly T[]): number;
lastIndexOf<T>(target: T): (list: readonly T[]) => number;
R.lastIndexOf source
import { equals } from './equals'

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

  let index = list.length

  while (--index > 0){
    if (equals(list[ index ], target)){
      return index
    }
  }

  return -1
}
Tests
import { lastIndexOf } from './lastIndexOf'

test('happy', () => {
  const a = lastIndexOf(1, [ 1, 2, 3, 1, 2 ])
  const b = lastIndexOf(1)([ 1, 2, 3, 1, 2 ])

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

test('false', () => {
  const a = lastIndexOf(10, [ 1, 2, 3, 1, 2 ])

  expect(a).toEqual(-1)
})
Typescript test
import {lastIndexOf} from 'rambda'

const list = [1, 2, 3]

describe('R.lastIndexOf', () => {
  it('happy', () => {
    const result = lastIndexOf(2, list)
    result // $ExpectType number
  })
  it('curried', () => {
    const result = lastIndexOf(2)(list)
    result // $ExpectType number
  })
})
Rambda is faster than Ramda with 42.38%
const R = require('../../dist/rambda.js')

const isEven = n => n % 2 === 0
const arr = [ 1, 3, 5, 7, 9, 11 ]

const lastIndexOf = [
  {
    label : 'Rambda',
    fn    : () => {
      R.lastIndexOf(1, [ 1, 2, 3, 1, 2 ])
      R.lastIndexOf(1)([ 1, 2, 3, 1, 2 ])
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.lastIndexOf(1, [ 1, 2, 3, 1, 2 ])
      Ramda.lastIndexOf(1)([ 1, 2, 3, 1, 2 ])
    },
  },
]

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

length

length<T>(input: readonly 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: readonly T[]): number;
R.length source
export function length(x){
  if (!x && x !== '' || x.length === undefined){
    return NaN
  }

  return x.length
}
Tests
import { length } from './length'

test('happy', () => {
  expect(length('foo')).toEqual(3)
  expect(length([ 1, 2, 3 ])).toEqual(3)
  expect(length([])).toEqual(0)
})

test('with empty string', () => {
  expect(length('')).toEqual(0)
})

test('with bad input returns NaN', () => {
  expect(length(0)).toBeNaN()
  expect(length({})).toBeNaN()
  expect(length(null)).toBeNaN()
  expect(length(undefined)).toBeNaN()
})

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

lens

lens<T, U, V>(getter: (s: T) => U, setter: (a: U, s: T) => V): Lens

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<T, U, V>(getter: (s: T) => U, setter: (a: U, s: T) => V): Lens;
R.lens source
export function lens(getter, setter){
  return function (functor){
    return function (target){
      return functor(getter(target)).map(focus => setter(focus, target))
    }
  }
}
Typescript test
import {lens, assoc} from 'rambda'

interface Input {
  foo: string,
}

describe('R.lens', () => {
  it('happy', () => {
    const fn = lens<Input, string, string>((x: Input) => {
      x.foo // $ExpectType string
      return x.foo
    }, assoc('name'))
    fn // $ExpectType Lens
  })
})

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

lensIndex

lensIndex(index: number): Lens

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(index: number): Lens;
R.lensIndex source
import { lens } from './lens'
import { nth } from './nth'
import { update } from './update'

export function lensIndex(index){
  return lens(nth(index), update(index))
}
Tests
import { compose } from './compose'
import { keys } from './keys'
import { lensIndex } from './lensIndex'
import { over } from './over'
import { set } from './set'
import { view } from './view'

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)).toEqual(undefined)
})

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)).toEqual(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
  ))).toEqual(0)
})

test('get (set(set s v1) v2) === v2', () => {
  expect(view(lensIndex(0),
    set(
      lensIndex(0), 11, set(
        lensIndex(0), 10, testList
      )
    ))).toEqual(11)
})
Typescript test
import {view, lensIndex} from 'rambda'

interface Input {
  a: number,
}
const testList: Input[] = [{a: 1}, {a: 2}, {a: 3}]

describe('R.lensIndex', () => {
  it('happy', () => {
    const result = view<Input[], Input>(lensIndex(0), testList)
    result // $ExpectType Input
    result.a // $ExpectType number
  })
})

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

lensPath

lensPath(path: RamdaPath): Lens

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(path: RamdaPath): Lens;
lensPath(path: string): Lens;
R.lensPath source
import {assocPath} from './assocPath'
import {lens} from './lens'
import {path} from './path'

export function lensPath(key) {
  return lens(path(key), assocPath(key))
}
Tests
import { compose } from './compose'
import { identity } from './identity'
import { inc } from './inc'
import { lensPath } from './lensPath'
import { lensProp } from './lensProp'
import { over } from './over'
import { set } from './set'
import { view } from './view'

const testObj = {
  a : [ { b : 1 }, { b : 2 } ],
  d : 3,
}

test('view', () => {
  expect(view(lensPath('d'), testObj)).toEqual(3)
  expect(view(lensPath('a.0.b'), testObj)).toEqual(1)
  // this is different to ramda, as ramda will return a clone of the input object
  expect(view(lensPath(''), testObj)).toEqual(undefined)
})

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
  )).toEqual(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)).toEqual(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
  ))).toEqual(0)
  expect(view(lensPath([ 'a', 0, 'b' ]), set(
    lensPath([ 'a', 0, 'b' ]), 0, testObj
  ))).toEqual(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
    )
  ))).toEqual(11)
  expect(view(lensPath(q), set(
    lensPath(q), 11, set(
      lensPath(q), 10, testObj
    )
  ))).toEqual(11)
})
Typescript test
import {lensPath, view} from 'rambda'

interface Input {
  foo: number[],
  bar: {
    a: string,
    b: string,
  },
}

const testObject: Input = {
  foo: [1, 2],
  bar: {
    a: 'x',
    b: 'y',
  },
}

const path = lensPath(['bar', 'a'])
const pathAsString = lensPath('bar.a')

describe('R.lensPath', () => {
  it('happy', () => {
    const result = view<Input, string>(path, testObject)
    result // $ExpectType string
  })
  it('using string as path input', () => {
    const result = view<Input, string>(pathAsString, testObject)
    result // $ExpectType string
  })
})

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

lensProp

lensProp(prop: string): {
  <T, U>(obj: T): U

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(prop: string): {
  <T, U>(obj: T): U;
  set<T, U, V>(val: T, obj: U): V;
};
R.lensProp source
import { assoc } from './assoc'
import { lens } from './lens'
import { prop } from './prop'

export function lensProp(key){
  return lens(prop(key), assoc(key))
}
Tests
import { compose } from './compose'
import { identity } from './identity'
import { inc } from './inc'
import { lensProp } from './lensProp'
import { over } from './over'
import { set } from './set'
import { view } from './view'

const testObj = {
  a : 1,
  b : 2,
  c : 3,
}

test('focuses object the specified object property', () => {
  expect(view(lensProp('a'), testObj)).toEqual(1)
})

test('returns undefined if the specified property does not exist', () => {
  expect(view(lensProp('X'), testObj)).toEqual(undefined)
})

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)).toEqual(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
  ))).toEqual(0)
})

test('get (set(set s v1) v2) === v2', () => {
  expect(view(lensProp('a'),
    set(
      lensProp('a'), 11, set(
        lensProp('a'), 10, testObj
      )
    ))).toEqual(11)
})
Typescript test
import {lensProp, view} from 'rambda'

interface Input {
  foo: string,
}

const testObject: Input = {
  foo: 'Led Zeppelin',
}

const lens = lensProp('foo')

describe('R.lensProp', () => {
  it('happy', () => {
    const result = view<Input, string>(lens, testObject)
    result // $ExpectType string
  })
})

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

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, list),
  R.map(fnWhenObject, obj)
]
// => [ [1, 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: readonly T[]): readonly U[];
map<T, U>(fn: Iterator<T, U>): (iterable: readonly T[]) => readonly U[];
map<T, U, S>(fn: ObjectIterator<T, U>): (iterable: Dictionary<T>) => Dictionary<U>;
map<T>(fn: Iterator<T, T>): (iterable: readonly T[]) => readonly T[];
map<T>(fn: Iterator<T, T>, iterable: readonly T[]): readonly T[];
R.map source
import { _isArray } from './_internals/_isArray'
import { _keys } from './_internals/_keys'

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){
  let index = 0
  const keys = _keys(obj)
  const len = keys.length
  const willReturn = {}

  while (index < len){
    const key = keys[ index ]
    willReturn[ key ] = fn(
      obj[ key ], key, obj
    )
    index++
  }

  return willReturn
}

export function map(fn, list){
  if (arguments.length === 1) return _list => map(fn, _list)
  if (list === undefined) return []
  if (_isArray(list)) return mapArray(fn, list)

  return mapObject(fn, list)
}
Tests
import { map } from './map'

const double = x => x * 2

const sampleObject = {
  a : 1,
  b : 2,
  c : 3,
  d : 4,
}

test('with array', () => {
  expect(map(double, [ 1, 2, 3 ])).toEqual([ 2, 4, 6 ])
})

test('with object', () => {
  const obj = {
    a : 1,
    b : 2,
  }

  expect(map(double, obj)).toEqual({
    a : 2,
    b : 4,
  })
})

test('pass input object as third argument', () => {
  const obj = {
    a : 1,
    b : 2,
  }
  const iterator = (
    val, prop, inputObject
  ) => {
    expect(inputObject).toEqual(obj)

    return val * 2
  }

  expect(map(iterator, obj)).toEqual({
    a : 2,
    b : 4,
  })
})

test('with object passes property as second argument', () => {
  map((_, prop) => {
    expect(typeof prop).toEqual('string')
  })(sampleObject)
})

/**
 * https://github.com/selfrefactor/rambda/issues/77
 */
test('when undefined instead of array', () => {
  expect(map(double, undefined)).toEqual([])
})
Typescript test
import {map} from 'rambda'

describe('R.map with arrays', () => {
  it('iterable returns the same type as the input', () => {
    const result = map<number>(
      (x: number) => {
        x // $ExpectType number
        return x + 2
      },
      [1, 2, 3]
    )
    result // $ExpectType number[]
  })
  it('iterable returns the same type as the input - curried', () => {
    const result = map<number>((x: number) => {
      x // $ExpectType number
      return x + 2
    })([1, 2, 3])
    result // $ExpectType number[]
  })
})

describe('R.map with objects', () => {
  it('iterable with all three arguments - curried', () => {
    // It requires dummy third typing argument
    // in order to identify compared to curry typings for arrays
    // ============================================
    const result = map<number, string, any>((a, b, c) => {
      a // $ExpectType number
      b // $ExpectType string
      c // $ExpectType Dictionary<number>
      return `${a}`
    })({a: 1, b: 2})
    result // $ExpectType Dictionary<string>
  })
  it('iterable with all three arguments', () => {
    const result = map<number, string>(
      (a, b, c) => {
        a // $ExpectType number
        b // $ExpectType string
        c // $ExpectType Dictionary<number>
        return `${a}`
      },
      {a: 1, b: 2}
    )
    result // $ExpectType Dictionary<string>
  })
  it('iterable with property argument', () => {
    const result = map<number, string>(
      (a, b) => {
        a // $ExpectType number
        b // $ExpectType string
        return `${a}`
      },
      {a: 1, b: 2}
    )
    result // $ExpectType Dictionary<string>
  })
  it('iterable with no property argument', () => {
    const result = map<number, string>(
      a => {
        a // $ExpectType number
        return `${a}`
      },
      {a: 1, b: 2}
    )
    result // $ExpectType Dictionary<string>
  })
})
Rambda is fastest. Ramda is 69.63% slower and Lodash is 4.68% slower
const R = require('../../dist/rambda.js')

const arr = [ 1, 2, 3, 4 ]
const fn = x => x * 2
const map = [
  {
    label : 'Rambda',
    fn    : () => {
      R.map(fn, arr)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.map(fn, arr)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.map(arr, fn)
    },
  },
]

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

match

match(regExpression: RegExp, str: string): readonly 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): readonly string[];
match(regExpression: RegExp): (str: string) => readonly 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'
import { match } from './match'

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)
  }).toThrowWithMessage(TypeError, 'Cannot read property \'match\' of null')
})
Typescript test
import {match} from 'rambda'

const str = 'foo bar'

describe('R.match', () => {
  it('happy', () => {
    const result = match(/foo/, str)
    result // $ExpectType string[]
  })
  it('curried', () => {
    const result = match(/foo/)(str)
    result // $ExpectType string[]
  })
})
Rambda is faster than Ramda with 46.75%
const R = require('../../dist/rambda.js')

const match = [
  {
    label : 'Rambda',
    fn    : () => {
      R.match(/a./g)('foo bar baz')
      R.match(/a./g, 'foo bar baz')
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.match(/a./g)('foo bar baz')
      Ramda.match(/a./g, 'foo bar baz')
    },
  },
]

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

mathMod

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

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

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'

test('with number', () => {
  expect(max(2, 1)).toBe(2)
})

test('with string', () => {
  expect(max('foo')('bar')).toBe('foo')
  expect(max('bar')('baz')).toBe('baz')
})
Typescript test
import {max} from 'rambda'

const first = 1
const second = 2

describe('R.max', () => {
  it('happy', () => {
    const result = max(first, second)
    result // $ExpectType 1 | 2
  })
  it('curried', () => {
    const result = max(first, second)
    result // $ExpectType 1 | 2
  })
  it('curried - cann pass type', () => {
    const result = max<number>(first, second)
    result // $ExpectType number
  })
  it('can pass type', () => {
    const result = max<number>(first, second)
    result // $ExpectType number
  })
})

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

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'

export function maxByFn(
  compareFn, x, y
){
  return compareFn(y) > compareFn(x) ? y : x
}

export const maxBy = curry(maxByFn)
Tests
import { maxBy } from './maxBy'

test('happy', () => {
  expect(maxBy(
    Math.abs, -5, 2
  )).toEqual(-5)
})

test('curried', () => {
  expect(maxBy(Math.abs)(2, -5)).toEqual(-5)
  expect(maxBy(Math.abs)(2)(-5)).toEqual(-5)
})
Typescript test
import {maxBy} from 'rambda'

const compareFn = (x: number) => x % 2 === 0 ? 1 : -1
const first = 1
const second = 2

describe('R.maxBy', () => {
  it('happy', () => {
    const result = maxBy(compareFn, first, second)
    result // $ExpectType 1 | 2
  })
})

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

mean

mean(list: readonly 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: readonly number[]): number;
R.mean source
import { sum } from './sum'

export function mean(list){
  return sum(list) / list.length
}
Tests
import { mean } from './mean'

test('happy', () => {
  expect(mean([ 2, 7 ])).toBe(4.5)
})

test('with NaN', () => {
  expect(mean([])).toBeNaN()
})
Typescript test
import {mean} from 'rambda'

describe('R.mean', () => {
  it('happy', () => {
    const result = mean([1, 2, 3])

    result // $ExpectType number
  })
})

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

median

median(list: readonly 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: readonly number[]): number;
R.median source
import { mean } from './mean'

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'

test('happy', () => {
  expect(median([ 2 ])).toEqual(2)
  expect(median([ 7, 2, 10, 2, 9 ])).toEqual(7)
})

test('with empty array', () => {
  expect(median([])).toBeNaN()
})
Typescript test
import {median} from 'rambda'

describe('R.median', () => {
  it('happy', () => {
    const result = median([1, 2, 3])

    result // $ExpectType number
  })
})

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

merge

merge<Output>(target: object, newProps: object): Output

It creates a copy of target object with overidden newProps properties.

const target = { 'foo': 0, 'bar': 1 }
const newProps = { 'foo': 7 }

const result = R.merge(target, newProps)
// => { 'foo': 7, 'bar': 1 }

Try this R.merge example in Rambda REPL

All Typescript definitions
merge<Output>(target: object, newProps: object): Output;
merge<Output>(target: object): (newProps: object) => Output;
R.merge source
export function merge(target, newProps){
  if (arguments.length === 1) return _newProps => merge(target, _newProps)

  return Object.assign(
    {}, target || {}, newProps || {}
  )
}
Tests
import { merge } from './merge'

const obj = {
  foo : 1,
  bar : 2,
}

test('happy', () => {
  expect(merge(obj, { bar : 20 })).toEqual({
    foo : 1,
    bar : 20,
  })
})

test('curry', () => {
  expect(merge(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(merge(null, undefined)).toEqual({})
  expect(merge(obj, null)).toEqual(obj)
  expect(merge(obj, undefined)).toEqual(obj)
  expect(merge(undefined, obj)).toEqual(obj)
})
Typescript test
import {merge} from 'rambda'

interface Output{
  foo: number
  bar: number
}

describe('R.merge', () => {
  const result = merge<Output>({foo: 1}, {bar: 2})
  const curriedResult = merge<Output>({foo: 1})({bar: 2})

  result.foo // $ExpectType number
  result.bar // $ExpectType number
  curriedResult.bar // $ExpectType number
})
Ramda is fastest. Rambda is 63.55% slower and Lodash is 55.25% slower
const R = require('../../dist/rambda.js')

const obj = { bar : 'yes' }
const a = {
  foo : 'bar',
  bar : 'baz',
}
const merge = [
  {
    label : 'Rambda',
    fn    : () => {
      R.merge(a, obj)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.merge(a, obj)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.merge(a, obj)
    },
  },
]

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

mergeAll

mergeAll<T>(list: readonly 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: readonly object[]): T;
mergeAll(list: readonly object[]): object;
R.mergeAll source
import { map } from './map'
import { merge } from './merge'

export function mergeAll(arr){
  let willReturn = {}
  map(val => {
    willReturn = merge(willReturn, val)
  }, arr)

  return willReturn
}
Tests
import { mergeAll } from './mergeAll'

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,
  })
})
Typescript test
import {mergeAll} from 'rambda'

describe('R.mergeAll', () => {
  it('with passing type', () => {
    interface Output {
      foo: number,
      bar: number,
    }
    const result = mergeAll<Output>([{foo: 1}, {bar: 2}])
    result.foo // $ExpectType number
    result.bar // $ExpectType number
  })

  it('without passing type', () => {
    const result = mergeAll([{foo: 1}, {bar: 2}])
    result // $ExpectType unknown
  })
})

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

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 { type } from './type'

export function mergeDeepRight(target, source){
  if (arguments.length === 1){
    return sourceHolder => mergeDeepRight(target, sourceHolder)
  }

  const willReturn = JSON.parse(JSON.stringify(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 'ramda'
import { mergeDeepRight } from './mergeDeepRight'

const slave = {
  name    : 'evilMe',
  age     : 10,
  contact : {
    a     : 1,
    email : '[email protected]',
  },
}
const master = {
  age     : 40,
  contact : { email : '[email protected]' },
  songs   : { title : 'Remains the same' },
}

test('happy', () => {
  const result = mergeDeepRight(slave, master)
  const curryResult = mergeDeepRight(slave)(master)
  const expected = {
    age     : 40,
    name    : 'evilMe',
    contact : {
      a     : 1,
      email : '[email protected]',
    },
    songs : { title : 'Remains the same' },
  }

  expect(result).toEqual(expected)
  expect(curryResult).toEqual(expected)
})

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)
})
Typescript test
import {mergeDeepRight} from 'rambda'

interface Output{
  foo: {
    bar: number
  }
}

describe('R.mergeDeepRight', () => {
  const result = mergeDeepRight<Output>({foo: {bar: 1}}, {foo: {bar: 2}})
  result.foo.bar // $ExpectType number
})

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

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 { merge } from './merge'

export function mergeLeft(x, y){
  if (arguments.length === 1) return _y => mergeLeft(x, _y)

  return merge(y, x)
}
Tests
import { mergeLeft } from './mergeLeft'

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)
})
Typescript test
import {mergeLeft} from 'rambda'

interface Output{
  foo: number
  bar: number
}

describe('R.mergeLeft', () => {
  const result = mergeLeft<Output>({foo: 1}, {bar: 2})
  const curriedResult = mergeLeft<Output>({foo: 1})({bar: 2})

  result.foo // $ExpectType number
  result.bar // $ExpectType number
  curriedResult.bar // $ExpectType number
})

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

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'

test('happy', () => {
  expect(min(2, 1)).toBe(1)
  expect(min(1)(2)).toBe(1)
})
Typescript test
import {min} from 'rambda'

const first = 1
const second = 2

describe('R.min', () => {
  it('happy', () => {
    const result = min(first, second)
    result // $ExpectType 1 | 2
  })
  it('curried', () => {
    const result = min(first, second)
    result // $ExpectType 1 | 2
  })
  it('curried - cann pass type', () => {
    const result = min<number>(first, second)
    result // $ExpectType number
  })
  it('can pass type', () => {
    const result = min<number>(first, second)
    result // $ExpectType number
  })
})

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

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'

export function minByFn(
  compareFn, x, y
){
  return compareFn(y) < compareFn(x) ? y : x
}

export const minBy = curry(minByFn)
Tests
import { minBy } from './minBy'

test('happy', () => {
  expect(minBy(
    Math.abs, -5, 2
  )).toEqual(2)
})

test('curried', () => {
  expect(minBy(Math.abs)(2, -5)).toEqual(2)
  expect(minBy(Math.abs)(2)(-5)).toEqual(2)
})
Typescript test
import {minBy} from 'rambda'

const compareFn = (x: number) => x % 2 === 0 ? 1 : -1
const first = 1
const second = 2

describe('R.minBy', () => {
  it('happy', () => {
    const result = minBy(compareFn, first, second)
    result // $ExpectType 1 | 2
  })
})

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

modulo

Curried version of x%y.

R.modulo(17, 3) // => 2

Try this R.modulo example in Rambda REPL

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

move

move<T>(fromIndex: number, toIndex: number, list: readonly T[]): readonly 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: readonly T[]): readonly T[];
move(fromIndex: number, toIndex: number): <T>(list: readonly T[]) => readonly T[];
move(fromIndex: number): {
    <T>(toIndex: number, list: readonly T[]): readonly T[];
    (toIndex: number): <T>(list: readonly T[]) => readonly T[];
};
R.move source
import { curry } from './curry'

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 = list.slice()
  clone[ fromIndex ] = list[ toIndex ]
  clone[ toIndex ] = list[ fromIndex ]

  return clone
}

export const move = curry(moveFn)
Tests
import { move } from './move'
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
  )).toThrowWithMessage(Error, errorMessage)
  expect(() => move(
    -1, 0, list
  )).toThrowWithMessage(Error, errorMessage)
})

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)
})
Typescript test
import {move} from 'rambda'

const list = [1, 2, 3]

describe('R.move', () => {
  it('happy', () => {
    const result = move(0, 1, list)

    result // $ExpectType number[]
  })
  it('curried 1', () => {
    const result = move(0, 1)(list)

    result // $ExpectType number[]
  })
  it('curried 2', () => {
    const result = move(0)(1)(list)

    result // $ExpectType number[]
  })
})

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

multiply

Curried version of x*y.

R.multiply(2, 4) // => 8

Try this R.multiply example in Rambda REPL

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

negate

R.negate(420)// => -420

Try this R.negate example in Rambda REPL

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

none

none<T>(predicate: (x: T) => boolean, list: readonly 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: readonly T[]): boolean;
none<T>(predicate: (x: T) => boolean): (list: readonly 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 true
  }

  return false
}
Tests
import { none } from './none'

const isEven = n => n % 2 === 0
const isOdd = n => n % 2 === 1
const arr = [ 1, 3, 5, 7, 9, 11 ]

test('when true', () => {
  expect(none(isEven, arr)).toBeTrue()
})

test('when false curried', () => {
  expect(none(isOdd)(arr)).toBeFalse()
})
Typescript test
import {none} from 'rambda'

describe('R.none', () => {
  it('happy', () => {
    const result = none(
      x => {
        x // $ExpectType number
        return x > 0
      },
      [1, 2, 3]
    )
    result // $ExpectType boolean
  })
  it('curried needs a type', () => {
    const result = none<number>(x => {
      x // $ExpectType number
      return x > 0
    })([1, 2, 3])
    result // $ExpectType boolean
  })
})
Rambda is faster than Ramda with 98.22%
const R = require('../../dist/rambda.js')

const isEven = n => n % 2 === 0
const arr = [ 1, 3, 5, 7, 9, 11 ]

const none = [
  {
    label : 'Rambda',
    fn    : () => {
      R.none(isEven, arr)
      R.none(isEven)(arr)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.none(isEven, arr)
      Ramda.none(isEven)(arr)
    },
  },
]

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

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'

test('not', () => {
  expect(not(false)).toEqual(true)
  expect(not(true)).toEqual(false)
  expect(not(0)).toEqual(true)
  expect(not(1)).toEqual(false)
})
Typescript test
import {not} from 'rambda'

describe('R.not', () => {
  it('happy', () => {
    const result = not(4)

    result // $ExpectType boolean
  })
})

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

nth

nth<T>(index: number, list: readonly T[]): T | undefined

Curried version of list[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<T>(index: number, list: readonly T[]): T | undefined;	
nth(index: number): <T>(list: readonly T[]) => T | undefined;
R.nth source
export function nth(index, list){
  if (arguments.length === 1) return _list => nth(index, _list)

  const idx = index < 0 ? list.length + index : index

  return Object.prototype.toString.call(list) === '[object String]' ?
    list.charAt(idx) :
    list[ idx ]
}
Tests
import { nth } from './nth'

test('happy', () => {
  expect(nth(2, [ 1, 2, 3, 4 ])).toEqual(3)
})

test('with curry', () => {
  expect(nth(2)([ 1, 2, 3, 4 ])).toEqual(3)
})

test('with string', () => {
  expect(nth(2)('foo')).toEqual('o')
})

test('with negative index', () => {
  expect(nth(-3)([ 1, 2, 3, 4 ])).toEqual(2)
})
Typescript test
import {nth} from 'rambda'

const list = [1, 2, 3]

describe('R.nth', () => {
  it('happy', () => {
    const result = nth(4, list)

    result // $ExpectType number | undefined
  })
  it('curried', () => {
    const result = nth(1)(list)

    result // $ExpectType number | undefined
  })
})

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

objOf

objOf<T, K extends string>(key: K, value: T): Record<K, T>

It returns a new object with the provided key and value.

const result = [
  R.objOf('foo', 42),
  R.objOf(null, undefined),
]
// => [{foo: 42}, {null: undefined}]

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 } from "./objOf";
import { objOf as objOfRamda } from "ramda";
import { compareCombinations } from "./_internals/testUtils";

test("happy", function () {
  expect(objOf("foo", 42)).toEqual({ foo: 42 });
});

test("with bad inputs", function () {
  expect(objOf(null, undefined)).toEqual({ null: undefined });
});

test("curried", function () {
  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(`
        Object {
          "ERRORS_MESSAGE_MISMATCH": 0,
          "ERRORS_TYPE_MISMATCH": 0,
          "RESULTS_MISMATCH": 0,
          "SHOULD_NOT_THROW": 0,
          "SHOULD_THROW": 0,
        }
      `);
    },
    fn: objOf,
    fnRamda: objOfRamda,
  });
});
Typescript test
import {objOf} from 'rambda'

const key = 'foo'
const value = 42

describe('R.objOf', () => {
  it('happy', () => {
    const result = objOf(key, value)

    result.foo // $ExpectType number
  })
  it('curried', () => {
    const result = objOf(key)(value)

    result.foo // $ExpectType number
  })
})
const R = require('../../dist/rambda.js')

const key = 'foo'
const value = 42

const assoc = [
  {
    label : 'Rambda',
    fn    : () => {
      R.objOf(
        key, value
      )
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.objOf(
        key, value
      )
    },
  },
]

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

of

of<T>(x: T): readonly T[]
R.of(null); // => [null]
R.of([42]); // => [[42]]

Try this R.of example in Rambda REPL

All Typescript definitions
of<T>(x: T): readonly T[];
R.of source
export function of(value){
  return [ value ]
}
Tests
import { of } from './of'

test('happy', () => {
  expect(of(3)).toEqual([ 3 ])

  expect(of(null)).toEqual([ null ])
})
Typescript test
import {of} from 'ramda'

const list = [1, 2, 3]

describe('R.of', () => {
  it('happy', () => {
    const result = of(4)

    result // $ExpectType number[]
  })
  it('curried', () => {
    const result = of(list)

    result // $ExpectType number[][]
  })
})

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

omit

omit<T, K extends string>(propsToOmit: readonly 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, obj), 
  R.omit(propsToOmitList, obj) 
]
// => [{b: 2}, {b: 2}]

Try this R.omit example in Rambda REPL

All Typescript definitions
omit<T, K extends string>(propsToOmit: readonly K[], obj: T): Omit<T, K>;
omit<K extends string>(propsToOmit: readonly 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
export function omit(propsToOmit, obj){
  if (arguments.length === 1) return _obj => omit(propsToOmit, _obj)

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

  const propsToOmitValue =
    typeof propsToOmit === 'string' ? propsToOmit.split(',') : propsToOmit

  const willReturn = {}

  for (const key in obj){
    if (!propsToOmitValue.includes(key)){
      willReturn[ key ] = obj[ key ]
    }
  }

  return willReturn
}
Tests
import { omit } from './omit'

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('with null', () => {
  expect(omit('a,b', null)).toEqual(undefined)
})

test('doesn\'t work with number as property', () => {
  expect(omit([ 42 ], {
    a  : 1,
    42 : 2,
  })).toEqual({
    42 : 2,
    a  : 1,
  })
})

test('happy', () => {
  expect(omit([ 'a', 'c' ])({
    a : 'foo',
    b : 'bar',
    c : 'baz',
  })).toEqual({ b : 'bar' })
})
Typescript test
import {omit} from 'rambda'

describe('R.omit with array as props input', () => {
  it('allow Typescript to infer object type', () => {
    const input = {a: 'foo', b: 2, c: 3, d: 4}
    const result = omit(['b,c'], input)

    result.a // $ExpectType string
    result.d // $ExpectType number

    const curriedResult = omit(['a,c'], input)

    curriedResult.a // $ExpectType string
    curriedResult.d // $ExpectType number
  })

  it('declare type of input object', () => {
    interface Input {
      a: string,
      b: number,
      c: number,
      d: number,
    }
    const input: Input = {a: 'foo', b: 2, c: 3, d: 4}
    const result = omit(['b,c'], input)
    result // $ExpectType Pick<Input, "b" | "a" | "c" | "d">

    result.a // $ExpectType string
    result.d // $ExpectType number

    const curriedResult = omit(['a,c'], input)

    curriedResult.a // $ExpectType string
    curriedResult.d // $ExpectType number
  })
})

describe('R.omit with string as props input', () => {
  interface Output {
    b: number,
    d: number,
  }

  it('explicitly declare output', () => {
    const result = omit<Output>('a,c', {a: 1, b: 2, c: 3, d: 4})
    result // $ExpectType Output
    result.b // $ExpectType number

    const curriedResult = omit<Output>('a,c')({a: 1, b: 2, c: 3, d: 4})

    curriedResult.b // $ExpectType number
  })

  it('explicitly declare input and output', () => {
    interface Input {
      a: number,
      b: number,
      c: number,
      d: number,
    }
    const result = omit<Input, Output>('a,c', {a: 1, b: 2, c: 3, d: 4})
    result // $ExpectType Output
    result.b // $ExpectType number

    const curriedResult = omit<Input, Output>('a,c')({
      a: 1,
      b: 2,
      c: 3,
      d: 4,
    })

    curriedResult.b // $ExpectType number
  })

  it('without passing type', () => {
    const result = omit('a,c', {a: 1, b: 2, c: 3, d: 4})
    result // $ExpectType unknown
  })
})
Rambda is fastest. Ramda is 70.66% slower and Lodash is 97.56% slower
const R = require('../../dist/rambda.js')

const obj = {
  a : 'foo',
  b : 'bar',
  c : 'baz',
}
const toOmit = [ 'a', 'c' ]
const omit = [
  {
    label : 'Rambda',
    fn    : () => {
      R.omit(toOmit, obj)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.omit(toOmit, obj)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.omit(obj, toOmit)
    },
  },
]

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

once

once<T extends (...args: readonly any[]) => any>(func: T): 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 (...args: readonly any[]) => any>(func: T): T;
R.once source
import { curry } from './curry'

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'

test('with counter', () => {
  let counter = 0
  const runOnce = once(x => {
    counter++

    return x + 2
  })
  expect(runOnce(1)).toEqual(3)
  runOnce(1)
  runOnce(1)
  runOnce(1)
  expect(counter).toEqual(1)
})

test('happy path', () => {
  const addOneOnce = once((
    a, b, c
  ) => a + b + c, 1)

  expect(addOneOnce(
    10, 20, 30
  )).toBe(60)
  expect(addOneOnce(40)).toEqual(60)
})
Typescript test
import {once} from 'rambda'

describe('R.once', () => {
  it('happy', () => {
    const runOnce = once((x: number) => {
      return x + 2
    })

    const result = runOnce(1)
    result // $ExpectType number
  })
})

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

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'

test('happy', () => {
  expect(or(0, 'foo')).toBe('foo')
  expect(or(true, true)).toBeTrue()
  expect(or(false)(true)).toBeTrue()
  expect(or(false, false)).toBeFalse()
})
Typescript test
import {or} from 'ramda'

describe('R.or', () => {
  it('happy', () => {
    const result = or(true, false)
    result // $ExpectType boolean
  })
  it('curried', () => {
    const result = or(1)('foo')
    result // $ExpectType number | "foo"
  })
})

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

over

over<T>(lens: Lens, fn: Arity1Fn, value: T): T

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<T>(lens: Lens, fn: Arity1Fn, value: T): T;
over<T>(lens: Lens, fn: Arity1Fn, value: readonly T[]): readonly T[];
over(lens: Lens, fn: Arity1Fn): <T>(value: T) => T;
over(lens: Lens, fn: Arity1Fn): <T>(value: readonly T[]) => readonly T[];
over(lens: Lens): <T>(fn: Arity1Fn, value: T) => T;
over(lens: Lens): <T>(fn: Arity1Fn, value: readonly T[]) => readonly T[];
R.over source
import { curry } from './curry'

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'
import { lens } from './lens'
import { lensIndex } from './lensIndex'
import { lensPath } from './lensPath'
import { over } from './over'
import { prop } from './prop'
import { toUpper } from './toUpper'

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' ])
})
Rambda is faster than Ramda with 50.77%
const R = require('../../dist/rambda.js')

const testObj = { a : 1 }

const last = [
  {
    label : 'Rambda',
    fn    : () => {
      R.over(
        R.lensProp('a'), R.inc, testObj
      )
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.over(
        Ramda.lensProp('a'), Ramda.inc, testObj
      )
    },
  },
]

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

partial

partial<V0, V1, T>(fn: (x0: V0, x1: V1) => T, args: readonly [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: readonly [V0]): (x1: V1) => T;
partial<V0, V1, V2, T>(fn: (x0: V0, x1: V1, x2: V2) => T, args: readonly [V0, V1]): (x2: V2) => T;
partial<V0, V1, V2, T>(fn: (x0: V0, x1: V1, x2: V2) => T, args: readonly [V0]): (x1: V1, x2: V2) => T;
partial<V0, V1, V2, V3, T>(fn: (x0: V0, x1: V1, x2: V2, x3: V3) => T, args: readonly [V0, V1, V2]): (x2: V3) => T;
partial<V0, V1, V2, V3, T>(fn: (x0: V0, x1: V1, x2: V2, x3: V3) => T, args: readonly [V0, V1]): (x2: V2, x3: V3) => T;
partial<V0, V1, V2, V3, T>(fn: (x0: V0, x1: V1, x2: V2, x3: V3) => T, args: readonly [V0]): (x1: V1, x2: V2, x3: V3) => T;
partial<T>(fn: (...a: readonly any[]) => T, args: readonly any[]): (...x: readonly any[]) => T;
R.partial source
export function partial(fn, ...args){
  const len = fn.length

  return (...rest) => {
    if (args.length + rest.length >= len){
      return fn(...args, ...rest)
    }

    return partial(fn, ...[ ...args, ...rest ])
  }
}
Tests
import { partial } from './partial'
import { type } from './type'

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')).toBe('Hello, Ms. foo bar!')
  expect(sayHelloRamda('foo', 'bar')).toBe('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
  )).toBe('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')).toBe('Hello, Ms. Jane Jones!')
})
Typescript test
import {partial} from 'rambda'

describe('R.partial', () => {
  it('happy', () => {
    function greet(
      salutation: string,
      title: string,
      firstName: string,
      lastName: string
    ) {
      return `${salutation}, ${title} ${firstName} ${lastName}!`
    }

    const sayHello = partial(greet, ['Hello'])
    const sayHelloToMs = partial(sayHello, ['Ms.'])
    const result = sayHelloToMs('Jane', 'Jones')
    result // $ExpectType string
  })
})

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

partition

partition<T>(
  predicate: Predicate<T>,
  input: readonly T[]
): readonly [readonly T[], readonly T[]]

It will return array of two objects/arrays according to predicate function. The first member holds all instanses 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, obj)
]
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: readonly T[]
): readonly [readonly T[], readonly T[]];
partition<T>(
  predicate: Predicate<T>
): (input: readonly T[]) => readonly [readonly T[], readonly T[]];
partition<T>(
  predicate: (x: T, prop?: string) => boolean,
  input: { readonly [key: string]: T}
): readonly [{ readonly [key: string]: T}, { readonly [key: string]: T}];
partition<T>(
  predicate: (x: T, prop?: string) => boolean
): (input: { readonly [key: string]: T}) => readonly [{ readonly [key: string]: T}, { readonly [key: string]: T}];
R.partition source
import { _isArray } from './_internals/_isArray'

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){
  const yes = []
  const no = []
  let counter = -1

  while (counter++ < list.length - 1){
    if (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'

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)
})
Typescript test
import {partition} from 'rambda'

describe('R.partition', () => {
  it('with array', () => {
    const predicate = (x: number) => {
      return x > 2
    }
    const list = [1, 2, 3, 4]

    const result = partition(predicate, list)
    const curriedResult = partition(predicate)(list)
    result // $ExpectType [number[], number[]]
    curriedResult // $ExpectType [number[], number[]]
  })

  /*
    TODO
    revert to old version of `dtslint` and `R.partition` typing
    as there is diff between VSCode types(correct) and dtslint(incorrect)
    
    it('with object', () => {
      const predicate = (value: number, prop?: string) => {
        return value > 2
      }
      const hash = {
        a: 1,
        b: 2,
        c: 3,
        d: 4,
      }
  
      const result = partition(predicate, hash)
      const curriedResult = partition(predicate)(hash)
      result[0] // $xExpectType { [key: string]: number; }
      result[1] // $xExpectType { [key: string]: number; }
      curriedResult[0] // $xExpectType { [key: string]: number; }
      curriedResult[1] // $xExpectType { [key: string]: number; }
    })
    */
})

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

path

path<Input, T>(pathToSearch: Path, obj: Input): T | undefined

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 anotation 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<Input, T>(pathToSearch: Path, obj: Input): T | undefined;
path<T>(pathToSearch: Path, obj: any): T | undefined;
path<T>(pathToSearch: Path): (obj: any) => T | undefined;
path<Input, T>(pathToSearch: Path): (obj: Input) => T | undefined;
R.path source
export function path(pathInput, obj){
  if (arguments.length === 1) return _obj => path(pathInput, _obj)

  if (obj === null || obj === undefined){
    return undefined
  }
  let willReturn = obj
  let counter = 0

  const pathArrValue =
    typeof pathInput === 'string' ? pathInput.split('.') : pathInput

  while (counter < pathArrValue.length){
    if (willReturn === null || willReturn === undefined){
      return undefined
    }
    willReturn = willReturn[ pathArrValue[ counter ] ]
    counter++
  }

  return willReturn
}
Tests
import { path } from './path'

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' } } })).toEqual('yes')
})

test('path', () => {
  expect(path([ 'foo', 'bar', 'baz' ])({ foo : { bar : { baz : 'yes' } } })).toEqual('yes')

  expect(path([ 'foo', 'bar', 'baz' ])(null)).toBeUndefined()

  expect(path([ 'foo', 'bar', 'baz' ])({ foo : { bar : 'baz' } })).toBeUndefined()
})
Typescript test
import {path} from 'rambda'

interface Input {
  a: number,
  b: {
    c: boolean,
  },
}

describe('R.path', () => {
  it('without specified input type', () => {
    const input = {a: 1, b: {c: true}}
    const result = path<boolean>('a.b.c', input)
    const curriedResult = path<boolean>('a.b.c')(input)
    result // $ExpectType boolean | undefined
    curriedResult // $ExpectType boolean | undefined
  })

  it('without specified output type', () => {
    const input = {a: 1, b: {c: true}}
    const result = path('a.b.c', input)
    result // $ExpectType unknown
  })

  it('with string as path', () => {
    const input: Input = {a: 1, b: {c: true}}
    const resultA = path<boolean>('a.b.c', input)
    const resultB = path<boolean>('a.b.c')(input)
    resultA // $ExpectType boolean | undefined
    resultB // $ExpectType boolean | undefined
  })
  it('with array as path', () => {
    const input: Input = {a: 1, b: {c: true}}
    const resultA = path<boolean>(['a', 'b', 'c'], input)
    const resultB = path<boolean>(['a', 'b', 'c'])(input)
    resultA // $ExpectType boolean | undefined
    resultB // $ExpectType boolean | undefined
  })
})

describe('path with specified input', () => {
  it('with string as path', () => {
    const input: Input = {a: 1, b: {c: true}}
    // const wrongInput = { a: 1, b: true }
    // const resultA = path<Input, boolean>('a.b.c', wrongInput)
    const resultA = path<Input, boolean>('a.b.c', input)
    const resultB = path<Input, boolean>('a.b.c')(input)
    resultA // $ExpectType boolean | undefined
    resultB // $ExpectType boolean | undefined
  })
  it('with array as path', () => {
    const input: Input = {a: 1, b: {c: true}}
    const resultA = path<Input, boolean>(['a', 'b', 'c'], input)
    const resultB = path<Input, boolean>(['a', 'b', 'c'])(input)
    resultA // $ExpectType boolean | undefined
    resultB // $ExpectType boolean | undefined
  })
})
Rambda is fastest. Ramda is 74.94% slower and Lodash is 5.72% slower
const R = require('../../dist/rambda.js')

const obj = { a : { b : 2 } }
const pathInput = [ 'a', 'b' ]

const path = [
  {
    label : 'Rambda',
    fn    : () => {
      R.path(pathInput, obj)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.path(pathInput, obj)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.get(obj, pathInput)
    },
  },
]

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

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'
import { equals } from './equals'
import { path } from './path'

function pathEqFn(
  pathToSearch, target, input
){
  return equals(path(pathToSearch, input), target)
}

export const pathEq = curry(pathEqFn)
Tests
import { pathEq } from './pathEq'

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()
})
Typescript test
import {pathEq} from 'rambda'

describe('R.pathEq', () => {
  it('with string path', () => {
    const pathToSearch = 'a.b.c'
    const input = {a: {b: {c: 1}}}
    const target = {c: 1}

    const result = pathEq(pathToSearch, input, target)
    const curriedResult = pathEq(pathToSearch, input, target)
    result // $ExpectType boolean
    curriedResult // $ExpectType boolean
  })

  it('with array path', () => {
    const pathToSearch = ['a', 'b', 'c']
    const input = {a: {b: {c: 1}}}
    const target = {c: 1}

    const result = pathEq(pathToSearch, input, target)
    const curriedResult = pathEq(pathToSearch, input, target)
    result // $ExpectType boolean
    curriedResult // $ExpectType boolean
  })
})

describe('with ramda specs', () => {
  const testPath = ['x', 0, 'y']
  const testObj = {
    x: [
      {y: 2, z: 3},
      {y: 4, z: 5},
    ],
  }

  const result1 = pathEq(testPath, 2, testObj)
  const result2 = pathEq(testPath, 2)(testObj)
  const result3 = pathEq(testPath)(2)(testObj)
  result1 // $ExpectType boolean
  result2 // $ExpectType boolean
  result3 // $ExpectType boolean
})

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

pathOr

pathOr<T>(defaultValue: T, pathToSearch: Path, obj: any): T

It reads obj input and returns either R.path(pathToSearch, obj) 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, obj) 
  R.pathOr(DEFAULT_VALUE, pathToSearchList, obj) 
  R.pathOr(DEFAULT_VALUE, 'a.b.c', obj) 
]
// => [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'
import { defaultTo } from './defaultTo'
import { path } from './path'

function pathOrFn(
  defaultValue, list, obj
){
  return defaultTo(defaultValue, path(list, obj))
}

export const pathOr = curry(pathOrFn)
Tests
import { pathOr } from './pathOr'

test('with undefined', () => {
  const result = pathOr(
    'foo', 'x.y', { x : { y : 1 } }
  )

  expect(result).toEqual(1)
})

test('with null', () => {
  const result = pathOr(
    'foo', 'x.y', null
  )

  expect(result).toEqual('foo')
})

test('with NaN', () => {
  const result = pathOr(
    'foo', 'x.y', NaN
  )

  expect(result).toEqual('foo')
})

test('curry case (x)(y)(z)', () => {
  const result = pathOr('foo')('x.y.z')({ x : { y : { a : 1 } } })

  expect(result).toEqual('foo')
})

test('curry case (x)(y,z)', () => {
  const result = pathOr('foo', 'x.y.z')({ x : { y : { a : 1 } } })

  expect(result).toEqual('foo')
})

test('curry case (x,y)(z)', () => {
  const result = pathOr('foo')('x.y.z', { x : { y : { a : 1 } } })

  expect(result).toEqual('foo')
})
Typescript test
import {pathOr} from 'rambda'

describe('R.pathOr', () => {
  it('with string path', () => {
    const x = pathOr<string>('foo', 'x.y', {x: {y: 'bar'}})
    x // $ExpectType string
  })
  it('with array path', () => {
    const x = pathOr<string>('foo', ['x', 'y'], {x: {y: 'bar'}})
    x // $ExpectType string
  })
  it('without passing type looks bad', () => {
    const x = pathOr('foo', 'x.y', {x: {y: 'bar'}})
    x // $ExpectType "foo"
  })
  it('curried', () => {
    const x = pathOr<string>('foo', 'x.y')({x: {y: 'bar'}})
    x // $ExpectType string
  })
})

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

paths

paths<Input, T>(pathsToSearch: readonly Path[], obj: Input): readonly (T | undefined)[]

It loops over members of pathsToSearch as singlePath and returns the array produced by R.path(singlePath, obj).

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.c.d',
  'a.b.c.d.e',
], obj)
// => [1, 2, undefined]

Try this R.paths example in Rambda REPL

All Typescript definitions
paths<Input, T>(pathsToSearch: readonly Path[], obj: Input): readonly (T | undefined)[];
paths<Input, T>(pathsToSearch: readonly Path[]): (obj: Input) => readonly (T | undefined)[];
paths<T>(pathsToSearch: readonly Path[], obj: any): readonly (T | undefined)[];
paths<T>(pathsToSearch: readonly Path[]): (obj: any) => readonly (T | undefined)[];
R.paths source
import { path } from './path'

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'

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 ])
})
Typescript test
import {paths} from 'rambda'

interface Input {
  a: number,
  b: number,
  c: number,
}

const input: Input = {a: 1, b: 2, c: 3}

describe('R.paths', () => {
  it('with dot notation', () => {
    const result = paths<number>(['a.b.c', 'foo.bar'], input)
    result // $ExpectType (number | undefined)[]
  })

  it('without type', () => {
    const result = paths(['a.b.c', 'foo.bar'], input)
    result // $ExpectType unknown[]
  })

  it('with array as path', () => {
    const result = paths<number>([['a', 'b', 'c'], ['foo.bar']], input)
    result // $ExpectType (number | undefined)[]
  })

  it('curried', () => {
    const result = paths<number>([['a', 'b', 'c'], ['foo.bar']])(input)
    result // $ExpectType (number | undefined)[]
  })
})

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

pick

pick<T, K extends string | number | symbol>(propsToPick: readonly 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 anotation 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, obj),
  R.pick(propsToPickList, obj),
  R.pick('a,bar', obj),
  R.pick('bar', obj),
  R.pick([0, 3], list),
  R.pick('0,3', list),
]

const expected = [
  {a:1, foo: 'cherry'},
  {a:1, foo: 'cherry'},
  {a:1},
  {},
  [1,4],
  [1,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: readonly K[], input: T): Pick<T, Exclude<keyof T, Exclude<keyof T, K>>>;
pick<K extends string | number | symbol>(propsToPick: readonly 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): (input: T) => U;
pick<T>(propsToPick: string, input: object): T;
pick<T>(propsToPick: string): (input: object) => T;
R.pick source
export function pick(propsToPick, input){
  if (arguments.length === 1) return _input => pick(propsToPick, _input)

  if (input === null || input === undefined){
    return undefined
  }
  const keys =
    typeof propsToPick === 'string' ? propsToPick.split(',') : propsToPick

  const willReturn = {}
  let counter = 0

  while (counter < keys.length){
    if (keys[ counter ] in input){
      willReturn[ keys[ counter ] ] = input[ keys[ counter ] ]
    }
    counter++
  }

  return willReturn
}
Tests
import { pick } from './pick'

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

test('props to pick is a string', () => {
  const result = pick('a,c', obj)
  const resultCurry = pick('a,c')(obj)
  const expectedResult = {
    a : 1,
    c : 3,
  }

  expect(result).toEqual(expectedResult)
  expect(resultCurry).toEqual(expectedResult)
})

test('when prop is missing', () => {
  const result = pick('a,d,f', obj)
  expect(result).toEqual({ a : 1 })
})

test('props to pick is an array', () => {
  expect(pick([ 'a', 'c' ])({
    a : 'foo',
    b : 'bar',
    c : 'baz',
  })).toEqual({
    a : 'foo',
    c : 'baz',
  })

  expect(pick([ 'a', 'd', 'e', 'f' ])({
    a : 'foo',
    b : 'bar',
    c : 'baz',
  })).toEqual({ a : 'foo' })

  expect(pick('a,d,e,f')(null)).toEqual(undefined)
})

test('works with list as input and number as props - props to pick is an array', () => {
  const result = pick([ 1, 2 ], [ 'a', 'b', 'c', 'd' ])
  expect(result).toEqual({
    1 : 'b',
    2 : 'c',
  })
})

test('works with list as input and number as props - props to pick is a string', () => {
  const result = pick('1,2', [ 'a', 'b', 'c', 'd' ])
  expect(result).toEqual({
    1 : 'b',
    2 : 'c',
  })
})

test('with symbol', () => {
  const symbolProp = Symbol('s')
  expect(pick([ symbolProp ], { [ symbolProp ] : 'a' })).toMatchInlineSnapshot(`
    Object {
      Symbol(s): "a",
    }
  `)
})
Typescript test
import {pick} from 'rambda'

const input = {a: 'foo', b: 2, c: 3, d: 4}

describe('R.pick with array as props input', () => {
  it('without passing type', () => {
    const result = pick(['a', 'c'], input)
    result.a // $ExpectType string
    result.c // $ExpectType number
  })
})

describe('R.pick with string as props input', () => {
  interface Input {
    a: string,
    b: number,
    c: number,
    d: number,
  }
  interface Output {
    a: string,
    c: number,
  }
  it('explicitly declare output', () => {
    const result = pick<Output>('a,c', input)
    result // $ExpectType Output
    result.a // $ExpectType string
    result.c // $ExpectType number

    const curriedResult = pick<Output>('a,c')(input)

    curriedResult.a // $ExpectType string
  })

  it('explicitly declare input and output', () => {
    const result = pick<Input, Output>('a,c', input)
    result // $ExpectType Output
    result.a // $ExpectType string

    const curriedResult = pick<Input, Output>('a,c')(input)

    curriedResult.a // $ExpectType string
  })

  it('without passing type', () => {
    const result = pick('a,c', input)
    result // $ExpectType unknown
  })
})
Rambda is fastest. Ramda is 26.29% slower and Lodash is 86.82% slower
const R = require('../../dist/rambda.js')

const obj = {
  a : 'foo',
  b : 'bar',
  c : 'baz',
}
const pickInput = [ 'a', 'c' ]
const pick = [
  {
    label : 'Rambda',
    fn    : () => {
      R.pick(pickInput, obj)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.pick(pickInput, obj)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.pick(obj, pickInput)
    },
  },
]

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

pickAll

pickAll<T, U>(propsToPick: readonly string[], input: T): U

Same as R.pick but it won't skip the missing props, i.e. it will assign them to undefined.

💥 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 propsToPick = 'a,foo,bar'
const propsToPickList = ['a', 'foo', 'bar']

const result = [
  R.pickAll(propsToPick, obj),
  R.pickAll(propsToPickList, obj),
  R.pickAll('a,bar', obj),
  R.pickAll('bar', obj),
]
const expected = [
  {a:1, foo: 'cherry', bar: undefined},
  {a:1, foo: 'cherry', bar: undefined},
  {a:1, bar: undefined},
  {bar: undefined}
]
// => `result` is equal to `expected`

Try this R.pickAll example in Rambda REPL

All Typescript definitions
pickAll<T, U>(propsToPick: readonly string[], input: T): U;
pickAll<T, U>(propsToPick: readonly string[]): (input: T) => U;
pickAll<T, U>(propsToPick: string, input: T): U;
pickAll<T, U>(propsToPick: string): (input: T) => U;
R.pickAll source
export function pickAll(propsToPick, obj){
  if (arguments.length === 1) return _obj => pickAll(propsToPick, _obj)

  if (obj === null || obj === undefined){
    return undefined
  }
  const keysValue =
    typeof propsToPick === 'string' ? propsToPick.split(',') : propsToPick

  const willReturn = {}
  let counter = 0

  while (counter < keysValue.length){
    if (keysValue[ counter ] in obj){
      willReturn[ keysValue[ counter ] ] = obj[ keysValue[ counter ] ]
    } else {
      willReturn[ keysValue[ counter ] ] = undefined
    }
    counter++
  }

  return willReturn
}
Tests
import { pickAll } from './pickAll'

test('when input is undefined or null', () => {
  expect(pickAll('a', null)).toBe(undefined)
  expect(pickAll('a', undefined)).toBe(undefined)
})

test('with string as condition', () => {
  const obj = {
    a : 1,
    b : 2,
    c : 3,
  }
  const result = pickAll('a,c', obj)
  const resultCurry = pickAll('a,c')(obj)
  const expectedResult = {
    a : 1,
    b : undefined,
    c : 3,
  }

  expect(result).toEqual(expectedResult)
  expect(resultCurry).toEqual(expectedResult)
})

test('with array as condition', () => {
  expect(pickAll([ 'a', 'b', 'c' ], {
    a : 'foo',
    c : 'baz',
  })).toEqual({
    a : 'foo',
    b : undefined,
    c : 'baz',
  })
})
Typescript test
import {pickAll} from 'rambda'

interface Input {
  a: string,
  b: number,
  c: number,
  d: number,
}
interface Output {
  a?: string,
  c?: number,
}
const input = {a: 'foo', b: 2, c: 3, d: 4}

describe('R.pickAll with array as props input', () => {
  it('without passing type', () => {
    const result = pickAll(['a', 'c'], input)
    result // $ExpectType unknown
  })
  it('without passing type + curry', () => {
    const result = pickAll(['a', 'c'])(input)
    result // $ExpectType unknown
  })
  it('explicitly passing types', () => {
    const result = pickAll<Input, Output>(['a', 'c'], input)
    result.a // $ExpectType string | undefined
    result.c // $ExpectType number | undefined
  })
  it('explicitly passing types + curry', () => {
    const result = pickAll<Input, Output>(['a', 'c'])(input)
    result.a // $ExpectType string | undefined
    result.c // $ExpectType number | undefined
  })
})

describe('R.pickAll with string as props input', () => {
  it('without passing type', () => {
    const result = pickAll('a,c', input)
    result // $ExpectType unknown
  })
  it('without passing type + curry', () => {
    const result = pickAll('a,c')(input)
    result // $ExpectType unknown
  })
  it('explicitly passing types', () => {
    const result = pickAll<Input, Output>('a,c', input)
    result.a // $ExpectType string | undefined
    result.c // $ExpectType number | undefined
  })
  it('explicitly passing types + curry', () => {
    const result = pickAll<Input, Output>('a,c')(input)
    result.a // $ExpectType string | undefined
    result.c // $ExpectType number | undefined
  })
})

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

pipe

It performs left-to-right function composition.

const result = R.pipe(
  R.filter(val => val > 2),
  R.map(a => a * 2)
)([1, 2, 3, 4])

// => [6, 8]

Try this R.pipe example in Rambda REPL

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

pluck

pluck<K extends keyof T, T>(property: K, list: readonly T[]): ReadonlyArray<T[K]>

It returns list of the values of property taken from the all objects inside list.

const list = [{a: 1}, {a: 2}, {b: 3}]
const property = 'a'

R.pluck(property, list) 
// => [1, 2]

Try this R.pluck example in Rambda REPL

All Typescript definitions
pluck<K extends keyof T, T>(property: K, list: readonly T[]): ReadonlyArray<T[K]>;
pluck<T>(property: number, list: ReadonlyArray<{ readonly [k: number]: T }>): readonly T[];
pluck<P extends string>(property: P): <T>(list: ReadonlyArray<Record<P, T>>) => readonly T[];
pluck(property: number): <T>(list: ReadonlyArray<{ readonly [k: number]: T }>) => readonly T[];
R.pluck source
import { map } from './map'

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

  const willReturn = []

  map(x => {
    if (x[ property ] !== undefined){
      willReturn.push(x[ property ])
    }
  }, list)

  return willReturn
}
Tests
import { pluck } from './pluck'

test('happy', () => {
  expect(pluck('a')([ { a : 1 }, { a : 2 }, { b : 1 } ])).toEqual([ 1, 2 ])
})

test('with number', () => {
  const input = [
    [ 1, 2 ],
    [ 3, 4 ],
  ]

  expect(pluck(0, input)).toEqual([ 1, 3 ])
})
Typescript test
import {pluck} from 'rambda'

describe('R.pluck', () => {
  it('with object', () => {
    interface ListMember {
      a: number,
      b: string,
    }
    const input: ListMember[] = [
      {a: 1, b: 'foo'},
      {a: 2, b: 'bar'},
    ]
    const resultA = pluck('a', input)
    const resultB = pluck('b')(input)
    resultA // $ExpectType number[]
    resultB // $ExpectType string[]
  })

  it('with array', () => {
    const input = [
      [1, 2],
      [3, 4],
      [5, 6],
    ]
    const result = pluck(0, input)
    const resultCurry = pluck(0)(input)
    result // $ExpectType number[]
    resultCurry // $ExpectType number[]
  })
})

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

prepend

prepend<T>(x: T, input: readonly T[]): readonly T[]

It adds element x at the beginning of list.

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

Try this R.prepend example in Rambda REPL

All Typescript definitions
prepend<T>(x: T, input: readonly T[]): readonly T[];
prepend<T>(x: T): (input: readonly T[]) => readonly T[];
R.prepend source
export function prepend(x, input){
  if (arguments.length === 1) return _input => prepend(x, _input)

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

  return [ x ].concat(input)
}
Tests
import { prepend } from './prepend'

test('happy', () => {
  expect(prepend('yes', [ 'foo', 'bar', 'baz' ])).toEqual([
    'yes',
    'foo',
    'bar',
    'baz',
  ])
})

test('with empty list', () => {
  expect(prepend('foo')([])).toEqual([ 'foo' ])
})

test('with string instead of array', () => {
  expect(prepend('foo')('bar')).toEqual([ 'foo', 'b', 'a', 'r' ])
})
Typescript test
import {prepend} from 'rambda'

const list = [1, 2, 3]

describe('R.prepend', () => {
  it('happy', () => {
    const result = prepend(4, list)

    result // $ExpectType number[]
  })
  it('curried', () => {
    const result = prepend(4)(list)

    result // $ExpectType number[]
  })
})

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

product

product(list: readonly number[]): number
R.product([ 2, 3, 4 ])
// => 24)

Try this R.product example in Rambda REPL

All Typescript definitions
product(list: readonly number[]): number;
R.product source
import { multiply } from './multiply'
import { reduce } from './reduce'

export const product = reduce(multiply, 1)
Tests
import { product } from './product'

test('happy', () => {
  expect(product([ 2, 3, 4 ])).toEqual(24)
})

test('bad input', () => {
  expect(product([ null ])).toEqual(0)
  expect(product([])).toEqual(1)
})
Typescript test
import {product} from 'rambda'

describe('R.product', () => {
  it('happy', () => {
    const result = product([1, 2, 3])

    result // $ExpectType number
  })
})

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

prop

prop<P extends keyof T, T>(propToFind: P, obj: T): T[P]

It returns the value of property propToFind in obj.

If there is no such property, it returns undefined.

const result = [
  R.prop('x', {x: 100}), 
  R.prop('x', {a: 1}) 
]
// => [100, undefined]

Try this R.prop example in Rambda REPL

All Typescript definitions
prop<P extends keyof T, T>(propToFind: P, obj: T): T[P];
prop<P extends string | number>(p: P): <T>(propToFind: Record<P, T>) => T;
prop<P extends keyof T, T>(p: P): (propToFind: Record<P, T>) => T;
R.prop source
export function prop(propToFind, obj){
  if (arguments.length === 1) return _obj => prop(propToFind, _obj)

  if (!obj) return undefined

  return obj[ propToFind ]
}
Tests
import { prop } from './prop'

test('prop', () => {
  expect(prop('foo')({ foo : 'baz' })).toEqual('baz')

  expect(prop('bar')({ foo : 'baz' })).toEqual(undefined)

  expect(prop('bar')(null)).toEqual(undefined)
})
Typescript test
import {prop} from 'rambda'

const obj = {a: 1, b: 'foo'}

describe('R.prop', () => {
  it('issue #553', () => {
    const result = prop('e', {e: 'test1', d: 'test2'})
    const curriedResult = prop<string>('e')({e: 'test1', d: 'test2'})

    result // $ExpectType string
    curriedResult // $ExpectType string
  })
  it('happy', () => {
    const result = prop('a', obj)

    result // $ExpectType number
  })
  it('curried', () => {
    const result = prop('b')(obj)

    result // $ExpectType string
  })
})

describe('with number as prop', () => {
  const list = [1, 2, 3]
  const index = 1
  it('happy', () => {
    const result = prop(index, list)

    result // $ExpectType number
  })
  it('curried require explicit type', () => {
    const result = prop<number>(index)(list)

    result // $ExpectType number
  })
})
Rambda is faster than Ramda with 89.89%
const R = require('../../dist/rambda.js')

const obj = {
  a : { c : 2 },
  b : 1,
}
const propInput = 'b'

const prop = [
  {
    label : 'Rambda',
    fn    : () => {
      R.prop(propInput, obj)
      R.prop(propInput)(obj)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.prop(propInput, obj)
      Ramda.prop(propInput)(obj)
    },
  },
]

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

propEq

propEq<K extends string | number>(propToFind: K, valueToMatch: any, obj: Record<K, any>): boolean

It returns true if obj has property propToFind and its value is equal to valueToMatch.

const obj = { foo: 'bar' }
const secondObj = { foo: 1 }

const propToFind = 'foo'
const valueToMatch = 'bar'

const result = [
  R.propEq(propToFind, valueToMatch, obj),
  R.propEq(propToFind, valueToMatch, secondObj)
]
// => [true, false]

Try this R.propEq example in Rambda REPL

All Typescript definitions
propEq<K extends string | number>(propToFind: K, valueToMatch: any, obj: Record<K, any>): boolean;
propEq<K extends string | number>(propToFind: K, valueToMatch: any): (obj: Record<K, any>) => boolean;
propEq<K extends string | number>(propToFind: K): {
  (valueToMatch: any, obj: Record<K, any>): boolean;
  (valueToMatch: any): (obj: Record<K, any>) => boolean;
};
R.propEq source
import { curry } from './curry'

function propEqFn(
  propToFind, valueToMatch, obj
){
  if (!obj) return false

  return obj[ propToFind ] === valueToMatch
}

export const propEq = curry(propEqFn)
Tests
import { propEq } from './propEq'

test('happy', () => {
  expect(propEq('foo', 'bar')({ foo : 'bar' })).toBeTrue()
  expect(propEq('foo', 'bar')({ foo : 'baz' })).toBeFalse()
  expect(propEq('foo')('bar')({ foo : 'baz' })).toBeFalse()
  expect(propEq(
    'foo', 'bar', null
  )).toBeFalse()
})
Typescript test
import {propEq} from 'rambda'

const property = 'foo'
const numberProperty = 1
const value = 'bar'
const obj = {[property]: value}
const objWithNumberIndex = {[numberProperty]: value}

describe('R.propEq', () => {
  it('happy', () => {
    const result = propEq(property, value, obj)
    result // $ExpectType boolean
  })

  it('number is property', () => {
    const result = propEq(1, value, objWithNumberIndex)
    result // $ExpectType boolean
  })

  it('with optional property', () => {
    interface MyType {
      optional?: string | number,
    }

    const myObject: MyType = {}
    const valueToFind = '1111'
    // $ExpectError
    propEq('optional', valueToFind, myObject)

    // $ExpectError
    propEq('optional', valueToFind, myObject)
  })

  it('imported from @types/ramda', () => {
    interface A {
      foo: string | null,
    }
    const obj: A = {
      foo: 'bar',
    }
    const value = ''
    const result = propEq('foo', value)(obj)
    result // $ExpectType boolean

    // $ExpectError
    propEq('bar', value)(obj)
  })
})
Rambda is faster than Ramda with 95.26%
const R = require('../../dist/rambda.js')

const obj = {
  a : { c : 2 },
  b : 1,
}
const propInput = 'b'
const expected = { c : 2 }

const propEq = [
  {
    label : 'Rambda',
    fn    : () => {
      R.propEq('a')(expected)(obj)

      R.propEq('a', expected)(obj)

      R.propEq(
        'a', expected, obj
      )
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.propEq('a')(expected)(obj)

      Ramda.propEq('a', expected)(obj)

      Ramda.propEq(
        'a', expected, obj
      )
    },
  },
]

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

propIs

propIs(type: any, name: string, obj: any): boolean

It returns true if property of obj is from target type.

const obj = {a:1, b: 'foo'}
const property = 'foo'

const result = [
  R.propIs(String, property, obj),
  R.propIs(Number, property, obj)
]
// => [true, false]

Try this R.propIs example in Rambda REPL

All Typescript definitions
propIs(type: any, name: string, obj: any): boolean;
propIs(type: any, name: string): (obj: any) => boolean;
propIs(type: any): {
    (name: string, obj: any): boolean;
    (name: string): (obj: any) => boolean;
};
R.propIs source
import { curry } from './curry'
import { is } from './is'

function propIsFn(
  targetPrototype, property, obj
){
  return is(targetPrototype, obj[ property ])
}

export const propIs = curry(propIsFn)
Tests
import { propIs } from './propIs'

const obj = { value : 1 }
const property = 'value'

test('when true', () => {
  expect(propIs(
    Number, property, obj
  )).toBeTrue()
})

test('when false', () => {
  expect(propIs(
    String, property, obj
  )).toBeFalse()
  expect(propIs(
    String, property, {}
  )).toBeFalse()
})
Typescript test
import {propIs} from 'rambda'

const property = 'a'
const obj = {a: 1}

describe('R.propIs', () => {
  it('happy', () => {
    const result = propIs(Number, property, obj)
    result // $ExpectType boolean
  })

  it('curried', () => {
    const result = propIs(Number, property)(obj)
    result // $ExpectType boolean
  })
})

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

propOr

propOr<T, P extends string>(defaultValue: T, property: P, obj: Partial<Record<P, T>> | undefined): T

It returns either defaultValue or the value of property in obj.

const obj = {a: 1}
const defaultValue = 'DEFAULT_VALUE'
const property = 'a'

const result = [
  R.propOr(defaultValue, property, obj),
  R.propOr(defaultValue, 'foo', obj)
]
// => [1, 'DEFAULT_VALUE']

Try this R.propOr example in Rambda REPL

All Typescript definitions
propOr<T, P extends string>(defaultValue: T, property: P, obj: Partial<Record<P, T>> | undefined): T;
propOr<T, P extends string>(defaultValue: T, property: P): (obj: Partial<Record<P, T>> | undefined) => T;
propOr<T>(defaultValue: T): {
  <P extends string>(property: P, obj: Partial<Record<P, T>> | undefined): T;
  <P extends string>(property: P): (obj: Partial<Record<P, T>> | undefined) => T;
}
R.propOr source
import { curry } from './curry'
import { defaultTo } from './defaultTo'

function propOrFn(
  defaultValue, property, obj
){
  if (!obj) return defaultValue

  return defaultTo(defaultValue, obj[ property ])
}

export const propOr = curry(propOrFn)
Tests
import { propOr } from './propOr'

test('propOr (result)', () => {
  const obj = { a : 1 }
  expect(propOr(
    'default', 'a', obj
  )).toEqual(1)
  expect(propOr(
    'default', 'notExist', obj
  )).toEqual('default')
  expect(propOr(
    'default', 'notExist', null
  )).toEqual('default')
})

test('propOr (currying)', () => {
  const obj = { a : 1 }
  expect(propOr('default')('a', obj)).toEqual(1)
  expect(propOr('default', 'a')(obj)).toEqual(1)
  expect(propOr('default')('notExist', obj)).toEqual('default')
  expect(propOr('default', 'notExist')(obj)).toEqual('default')
})
Typescript test
import {propOr} from 'rambda'

const obj = {foo: 'bar'}
const property = 'foo'
const fallback = 'fallback'

describe('R.propOr', () => {
  it('happy', () => {
    const result = propOr(fallback, property, obj)
    result // $ExpectType string
  })
  it('curry 1', () => {
    const result = propOr(fallback)(property, obj)
    result // $ExpectType string
  })
  it('curry 2', () => {
    const result = propOr(fallback, property)(obj)
    result // $ExpectType string
  })
  it('curry 3', () => {
    const result = propOr(fallback)(property)(obj)
    result // $ExpectType string
  })
})

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

props

props<P extends string, T>(propsToPick: readonly P[], obj: Record<P, T>): readonly T[]

It takes list with properties propsToPick and returns a list with property values in obj.

const result = [
  R.props(['a', 'b'], {a:1, c:3})
// => [1, undefined]

Try this R.props example in Rambda REPL

All Typescript definitions
props<P extends string, T>(propsToPick: readonly P[], obj: Record<P, T>): readonly T[];
props<P extends string>(propsToPick: readonly P[]): <T>(obj: Record<P, T>) => readonly T[];
props<P extends string, T>(propsToPick: readonly P[]): (obj: Record<P, T>) => readonly T[];
R.props source
import { _isArray } from './_internals/_isArray'
import { mapArray } from './map'

export function props(propsToPick, obj){
  if (arguments.length === 1){
    return _obj => props(propsToPick, _obj)
  }
  if (!_isArray(propsToPick)){
    throw new Error('propsToPick is not a list')
  }

  return mapArray(prop => obj[ prop ], propsToPick)
}
Tests
import { props } from './props'

const obj = {
  a : 1,
  b : 2,
}
const propsToPick = [ 'a', 'c' ]

test('happy', () => {
  const result = props(propsToPick, obj)
  expect(result).toEqual([ 1, undefined ])
})

test('curried', () => {
  const result = props(propsToPick)(obj)
  expect(result).toEqual([ 1, undefined ])
})

test('wrong input', () => {
  expect(() => props(null)(obj)).toThrow()
})
Typescript test
import {props} from 'rambda'

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

describe('R.props', () => {
  it('happy', () => {
    const result = props(['a', 'b'], obj)

    result // $ExpectType number[]
  })
  it('curried', () => {
    const result = props(['a', 'b'])(obj)

    result // $ExpectType number[]
  })
})

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

range

range(startInclusive: number, endExclusive: number): readonly number[]

It returns list of numbers between startInclusive to endExclusive markers.

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

Try this R.range example in Rambda REPL

All Typescript definitions
range(startInclusive: number, endExclusive: number): readonly number[];
range(startInclusive: number): (endExclusive: number) => readonly number[];
R.range source
export function range(start, end){
  if (arguments.length === 1) return _end => range(start, _end)

  if (Number.isNaN(Number(start)) || Number.isNaN(Number(end))){
    throw new TypeError('Both arguments to range must be numbers')
  }

  if (end < start) return []

  const len = end - start
  const willReturn = Array(len)

  for (let i = 0; i < len; i++){
    willReturn[ i ] = start + i
  }

  return willReturn
}
Tests
import { range } from './range'

test('happy', () => {
  expect(range(0, 10)).toEqual([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ])
})

test('end range is bigger than start range', () => {
  expect(range(7, 3)).toEqual([])
  expect(range(5, 5)).toEqual([])
})

test('with bad input', () => {
  const throwMessage = 'Both arguments to range must be numbers'
  expect(() => range('a', 6)).toThrowWithMessage(Error, throwMessage)
  expect(() => range(6, 'z')).toThrowWithMessage(Error, throwMessage)
})

test('curry', () => {
  expect(range(0)(10)).toEqual([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ])
})
Typescript test
import {range} from 'rambda'

describe('R.range', () => {
  it('happy', () => {
    const result = range(1, 4)

    result // $ExpectType number[]
  })
  it('curried', () => {
    const result = range(1)(4)

    result // $ExpectType number[]
  })
})
Lodash is fastest. Rambda is 95.17% slower and Ramda is 90.22% slower
const R = require('../../dist/rambda.js')

const start = 12
const end = 22
const range = [
  {
    label : 'Rambda',
    fn    : () => {
      R.range(start, end)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.range(start, end)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.range(start, end)
    },
  },
]

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

reduce

reduce<T, TResult>(reducer: (prev: TResult, current: T, i: number) => TResult, initialValue: TResult, list: readonly T[]): TResult

💥 It passes index of the list as third argument to reducer function.

const list = [1, 2, 3]
const initialValue = 10
const reducer = (prev, current) => prev * current

const result = R.reduce(reducer, initialValue, list)
// => 60

Try this R.reduce example in Rambda REPL

All Typescript definitions
reduce<T, TResult>(reducer: (prev: TResult, current: T, i: number) => TResult, initialValue: TResult, list: readonly T[]): TResult;
reduce<T, TResult>(reducer: (prev: TResult, current: T) => TResult, initialValue: TResult, list: readonly T[]): TResult;
reduce<T, TResult>(reducer: (prev: TResult, current: T, i?: number) => TResult): (initialValue: TResult, list: readonly T[]) => TResult;
reduce<T, TResult>(reducer: (prev: TResult, current: T, i?: number) => TResult, initialValue: TResult): (list: readonly T[]) => TResult;
R.reduce source
import { _isArray } from './_internals/_isArray'
import { _keys } from './_internals/_keys'
import { curry } from './curry'

function reduceFn(
  reducer, acc, list
){
  if (!_isArray(list)){
    throw new TypeError('reduce: list must be array or iterable')
  }
  let index = 0
  const len = list.length

  while (index < len){
    acc = reducer(
      acc, list[ index ], index, list
    )
    index++
  }

  return acc
}

export const reduce = curry(reduceFn)
Tests
import { reduce } from './reduce'

const reducer = (
  prev, current, i
) => {
  expect(i).toBeNumber()

  return prev + current
}
const initialValue = 1
const list = [ 1, 2, 3 ]

test('happy', () => {
  expect(reduce(
    reducer, initialValue, list
  )).toEqual(7)
})

test('with object as iterable', () => {
  expect(() =>
    reduce(
      reducer, initialValue, {
        a : 1,
        b : 2,
      }
    )).toThrowWithMessage(TypeError, 'reduce: list must be array or iterable')
})

test('with undefined as iterable', () => {
  expect(() => reduce(
    reducer, initialValue, undefined
  )).toThrowWithMessage(TypeError,
    'reduce: list must be array or iterable')
})
Typescript test
import {reduce} from 'rambda'

describe('R.reduce', () => {
  it('happy', () => {
    const result = reduce<number, number>(
      (acc, elem) => {
        acc // $ExpectType number
        elem // $ExpectType number
        return acc + elem
      },
      1,
      [1, 2, 3]
    )

    result // $ExpectType number
  })

  it('with two types', () => {
    const result = reduce<number, string>(
      (acc, elem) => {
        acc // $ExpectType string
        elem // $ExpectType number

        return `${acc}${elem}`
      },
      'foo',
      [1, 2, 3]
    )

    result // $ExpectType string
  })

  it('with index', () => {
    const result = reduce<number, number>(
      (acc, elem, i) => {
        acc // $ExpectType number
        elem // $ExpectType number
        i // $ExpectType number
        return acc + elem
      },
      1,
      [1, 2, 3]
    )

    result // $ExpectType number
  })

  it('fallback', () => {
    const result = reduce(
      (acc, val) => {
        acc // $ExpectType number
        return acc + val
      },
      1,
      [1, 2, 3]
    )

    result // $ExpectType number
  })

  it('fallback with index', () => {
    const result = reduce(
      (acc, val, i) => {
        acc // $ExpectType number
        i // $ExpectType number
        return acc + val
      },
      1,
      [1, 2, 3]
    )

    result // $ExpectType number
  })

  it('fallback with two types', () => {
    const result = reduce(
      (acc, val) => {
        acc // $ExpectType string
        return acc + val
      },
      'foo',
      [1, 2, 3]
    )

    result // $ExpectType string
  })
})
Lodash is fastest. Rambda is 52.76% slower and Ramda is 74.02% slower
const R = require('../../dist/rambda.js')

const fn = (acc, value) => acc + value
const holder = [ 1, 2, 3 ]
const acc = ''

const reduce = [
  {
    label : 'Rambda',
    fn    : () => {
      R.reduce(
        fn, acc, holder
      )
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.reduce(
        fn, acc, holder
      )
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.reduce(
        holder, fn, acc
      )
    },
  },
]

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

reject

reject<T>(predicate: Predicate<T>, list: readonly T[]): readonly T[]

It has the opposite effect of R.filter.

const list = [1, 2, 3, 4]
const obj = {a: 1, b: 2}
const predicate = x => x > 1

const result = [
  R.reject(predicate, list)
  R.reject(predicate, obj)
]
// => [[1, 2], {a: 1}]

Try this R.reject example in Rambda REPL

All Typescript definitions
reject<T>(predicate: Predicate<T>, list: readonly T[]): readonly T[];
reject<T>(predicate: Predicate<T>): (list: readonly T[]) => readonly T[];
reject<T>(predicate: Predicate<T>, obj: Dictionary<T>): Dictionary<T>;
reject<T, U>(predicate: Predicate<T>): (obj: Dictionary<T>) => Dictionary<T>;
R.reject source
import { filter } from './filter'

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

  return filter(x => !predicate(x), list)
}
Tests
import { reject } from './reject'

const isOdd = n => n % 2 === 1

test('with array', () => {
  expect(reject(isOdd)([ 1, 2, 3, 4 ])).toEqual([ 2, 4 ])
})

test('with object', () => {
  const obj = {
    a : 1,
    b : 2,
    c : 3,
    d : 4,
  }
  expect(reject(isOdd, obj)).toEqual({
    b : 2,
    d : 4,
  })
})
Typescript test
import {reject} from 'rambda'

describe('R.reject with array', () => {
  it('happy', () => {
    const result = reject(
      x => {
        x // $ExpectType number
        return x > 1
      },
      [1, 2, 3]
    )
    result // $ExpectType number[]
  })
  it('curried require explicit type', () => {
    const result = reject<number>(x => {
      x // $ExpectType number
      return x > 1
    })([1, 2, 3])
    result // $ExpectType number[]
  })
})

describe('R.reject with objects', () => {
  it('happy', () => {
    const result = reject(
      x => {
        x // $ExpectType number

        return x > 1
      },
      {a: 1, b: 2}
    )
    result // $ExpectType Dictionary<number>
  })
  it('curried require dummy type', () => {
    const result = reject<number, any>(x => {
      return x > 1
    })({a: 1, b: 2})
    result // $ExpectType Dictionary<number>
  })
})

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

repeat

repeat<T>(x: T): (timesToRepeat: number) => readonly T[]
R.repeat('foo', 3)
// => ['foo', 'foo', 'foo']

Try this R.repeat example in Rambda REPL

All Typescript definitions
repeat<T>(x: T): (timesToRepeat: number) => readonly T[];
repeat<T>(x: T, timesToRepeat: number): readonly T[];
R.repeat source
export function repeat(x, timesToRepeat){
  if (arguments.length === 1){
    return _timesToRepeat => repeat(x, _timesToRepeat)
  }

  return Array(timesToRepeat).fill(x)
}
Tests
import { repeat } from './repeat'

test('repeat', () => {
  expect(repeat('')(3)).toEqual([ '', '', '' ])
  expect(repeat('foo', 3)).toEqual([ 'foo', 'foo', 'foo' ])

  const obj = {}
  const arr = repeat(obj, 3)

  expect(arr).toEqual([ {}, {}, {} ])

  expect(arr[ 0 ] === arr[ 1 ]).toBeTrue()
})
Typescript test
import {repeat} from 'rambda'

describe('R.repeat', () => {
  it('happy', () => {
    const result = repeat(4, 7)

    result // $ExpectType number[]
  })
  it('curried', () => {
    const result = repeat(4)(7)

    result // $ExpectType number[]
  })
})
Lodash is fastest. Rambda is 85.91% slower and Ramda is 95.31% slower
const R = require('../../dist/rambda.js')

const num = 10
const str = 'foo'

const repeat = [
  {
    label : 'Rambda',
    fn    : () => {
      R.repeat(str, num)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.repeat(str, num)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.repeat(str, num)
    },
  },
]

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

replace

replace(strOrRegex: RegExp | string, replacer: string, str: string): string

It replaces strOrRegex found in str with replacer.

const strOrRegex = /o/g

const result = R.replace(strOrRegex, '|0|', 'foo')
// => 'f|0||0|'

Try this R.replace example in Rambda REPL

All Typescript definitions
replace(strOrRegex: RegExp | string, replacer: string, str: string): string;
replace(strOrRegex: RegExp | string, replacer: string): (str: string) => string;
replace(strOrRegex: RegExp | string): (replacer: string) => (str: string) => string;
R.replace source
import { curry } from './curry'

function replaceFn(
  pattern, replacer, str
){
  return str.replace(pattern, replacer)
}

export const replace = curry(replaceFn)
Tests
import { replace } from './replace'

test('happy', () => {
  expect(replace(
    'foo', 'yes', 'foo bar baz'
  )).toEqual('yes bar baz')
})

test('1', () => {
  expect(replace(/\s/g)('|')('foo bar baz')).toEqual('foo|bar|baz')
})

test('2', () => {
  expect(replace(/\s/g)('|', 'foo bar baz')).toEqual('foo|bar|baz')
})

test('3', () => {
  expect(replace(/\s/g, '|')('foo bar baz')).toEqual('foo|bar|baz')
})
Typescript test
import {replace} from 'rambda'

const str = 'foo bar foo'
const replacer = 'bar'

describe('R.replace', () => {
  it('happy', () => {
    const result = replace(/foo/g, replacer, str)

    result // $ExpectType string
  })
  it('with string as search pattern', () => {
    const result = replace('foo', replacer, str)

    result // $ExpectType string
  })
})

describe('R.replace - curried', () => {
  it('happy', () => {
    const result = replace(/foo/g, replacer)(str)

    result // $ExpectType string
  })
  it('with string as search pattern', () => {
    const result = replace('foo', replacer)(str)

    result // $ExpectType string
  })
})
Lodash is fastest. Rambda is 0.47% slower and Ramda is 28.13% slower
const R = require('../../dist/rambda.js')

const replace = [
  {
    label : 'Rambda',
    fn    : () => {
      R.replace(
        /\s/g, '|', 'foo bar baz'
      )
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.replace(
        /\s/g, '|', 'foo bar baz'
      )
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.replace(
        'foo bar baz', /\s/g, '|'
      )
    },
  },
]

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

reverse

reverse<T>(input: readonly T[]): readonly T[]

It returns a reversed copy of list or string input.

const result = [
  R.reverse('foo'),
  R.reverse([1, 2, 3])
]
// => ['oof', [3, 2, 1]

Try this R.reverse example in Rambda REPL

All Typescript definitions
reverse<T>(input: readonly T[]): readonly T[];
reverse(input: string): string;
R.reverse source
export function reverse(listOrString){
  if (typeof listOrString === 'string'){
    return listOrString.split('').reverse()
      .join('')
  }

  const clone = listOrString.slice()

  return clone.reverse()
}
Tests
import { reverse } from './reverse'

test('happy', () => {
  expect(reverse([ 1, 2, 3 ])).toEqual([ 3, 2, 1 ])
})

test('with string', () => {
  expect(reverse('baz')).toEqual('zab')
})

test('it doesn\'t mutate', () => {
  const arr = [ 1, 2, 3 ]

  expect(reverse(arr)).toEqual([ 3, 2, 1 ])

  expect(arr).toEqual([ 1, 2, 3 ])
})
Typescript test
import {reverse} from 'rambda'

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

describe('R.reverse', () => {
  it('happy', () => {
    const result = reverse(list)
    result // $ExpectType number[]
  })
})

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

set

set<T, U>(lens: Lens, replacer: U, obj: T): T

It returns a copied Object or Array with modified lens focus set to replacer value.

const input = {x: 1, y: 2}
const xLens = R.lensProp('x')

R.set(xLens, 4, input) // => {x: 4, y: 2}
R.set(xLens, 8, input) // => {x: 8, y: 2}

Try this R.set example in Rambda REPL

All Typescript definitions
set<T, U>(lens: Lens, replacer: U, obj: T): T;
set<U>(lens: Lens, replacer: U): <T>(obj: T) => T;
set(lens: Lens): <T, U>(replacer: U, obj: T) => T;
R.set source
import { always } from './always'
import { curry } from './curry'
import { over } from './over'

function setFn(
  lens, replacer, x
){
  return over(
    lens, always(replacer), x
  )
}

export const set = curry(setFn)
Tests
import { assoc } from './assoc'
import { lens } from './lens'
import { lensIndex } from './lensIndex'
import { lensPath } from './lensPath'
import { prop } from './prop'
import { set } from './set'

const testObject = {
  foo : 'bar',
  baz : {
    a : 'x',
    b : 'y',
  },
}

test('assoc lens', () => {
  const assocLens = lens(prop('foo'), assoc('foo'))
  const result = set(
    assocLens, 'FOO', testObject
  )
  const expected = {
    ...testObject,
    foo : 'FOO',
  }
  expect(result).toEqual(expected)
})

test('path lens', () => {
  const pathLens = lensPath('baz.a')
  const result = set(
    pathLens, 'z', testObject
  )
  const expected = {
    ...testObject,
    baz : {
      a : 'z',
      b : 'y',
    },
  }
  expect(result).toEqual(expected)
})

test('index lens', () => {
  const indexLens = lensIndex(0)

  const result = set(
    indexLens, 3, [ 1, 2 ]
  )
  expect(result).toEqual([ 3, 2 ])
})
Rambda is faster than Ramda with 36.26%
const R = require('../../dist/rambda.js')

const testObj = { a : 1 }

const last = [
  {
    label : 'Rambda',
    fn    : () => {
      R.set(
        R.lensProp('a'), 2, testObj
      )
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.set(
        Ramda.lensProp('a'), 2, testObj
      )
    },
  },
]

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

slice

slice(from: number, to: number, input: string): string
const list = [0, 1, 2, 3, 4, 5]
const str = 'FOO_BAR'
const from = 1
const to = 4

const result = [
  R.slice(str, to, list),
  R.slice(from, to, list)
]
// => ['OO_', [1, 2, 3]]

Try this R.slice example in Rambda REPL

All Typescript definitions
slice(from: number, to: number, input: string): string;
slice<T>(from: number, to: number, input: readonly T[]): readonly T[];
slice(from: number, to: number): {
  (input: string): string;
  <T>(input: readonly T[]): readonly T[];
};
slice(from: number): {
  (to: number, input: string): string;
  <T>(to: number, input: readonly T[]): readonly T[];
};
R.slice source
import { curry } from './curry'

function sliceFn(
  from, to, list
){
  return list.slice(from, to)
}

export const slice = curry(sliceFn)
Tests
import { slice } from './slice'

test('slice', () => {
  expect(slice(
    1, 3, [ 'a', 'b', 'c', 'd' ]
  )).toEqual([ 'b', 'c' ])
  expect(slice(
    1, Infinity, [ 'a', 'b', 'c', 'd' ]
  )).toEqual([ 'b', 'c', 'd' ])
  expect(slice(
    0, -1, [ 'a', 'b', 'c', 'd' ]
  )).toEqual([ 'a', 'b', 'c' ])
  expect(slice(
    -3, -1, [ 'a', 'b', 'c', 'd' ]
  )).toEqual([ 'b', 'c' ])
  expect(slice(
    0, 3, 'ramda'
  )).toEqual('ram')
})
Typescript test
import {slice} from 'rambda'

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

describe('R.slice', () => {
  it('happy', () => {
    const result = slice(1, 3, list)
    result // $ExpectType number[]
  })
  it('curried', () => {
    const result = slice(1, 3)(list)
    result // $ExpectType number[]
  })
})

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

sort

sort<T>(sortFn: (a: T, b: T) => number, list: readonly T[]): readonly T[]

It returns copy of list sorted by sortFn function.

💥 sortFn function must return a number.

const list = [
  {a: 2},
  {a: 3},
  {a: 1}
]
const sortFn = (x, y) => {
  return x.a > y.a ? 1 : -1
}

const result = R.sort(sortFn, list)
const expected = [
  {a: 1},
  {a: 2},
  {a: 3}
]
// => `result` is equal to `expected`

Try this R.sort example in Rambda REPL

All Typescript definitions
sort<T>(sortFn: (a: T, b: T) => number, list: readonly T[]): readonly T[];
sort<T>(sortFn: (a: T, b: T) => number): (list: readonly T[]) => readonly T[];
R.sort source
export function sort(sortFn, list){
  if (arguments.length === 1) return _list => sort(sortFn, _list)

  const clone = list.slice()

  return clone.sort(sortFn)
}
Tests
import { sort } from './sort'

const fn = (a, b) => a > b ? 1 : -1

test('sort', () => {
  expect(sort((a, b) => a - b)([ 2, 3, 1 ])).toEqual([ 1, 2, 3 ])
})

test('it doesn\'t mutate', () => {
  const list = [ 'foo', 'bar', 'baz' ]

  expect(sort(fn, list)).toEqual([ 'bar', 'baz', 'foo' ])

  expect(list[ 0 ]).toBe('foo')
  expect(list[ 1 ]).toBe('bar')
  expect(list[ 2 ]).toBe('baz')
})
Typescript test
import {sort} from 'rambda'

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

function sortFn(a: number, b: number): number {
  return a > b ? 1 : -1
}

describe('R.sort', () => {
  it('happy', () => {
    const result = sort(sortFn, list)
    result // $ExpectType number[]
  })
  it('curried', () => {
    const result = sort(sortFn)(list)
    result // $ExpectType number[]
  })
})
Rambda is faster than Ramda with 63.15%
const R = require('../../dist/rambda.js')

const list = [ 'foo', 'bar', 'baz' ]
const fn = (a, b) => a > b ? -1 : 1

const replace = [
  {
    label : 'Rambda',
    fn    : () => {
      R.sort(fn, list)
      R.sort(fn)(list)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.sort(fn, list)
      Ramda.sort(fn)(list)
    },
  },
]

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

sortBy

sortBy<T>(sortFn: (a: T) => Ord, list: readonly T[]): readonly T[]

It returns copy of list sorted by sortFn function.

💥 sortFn function must return a value to compare.

const list = [
  {a: 2},
  {a: 3},
  {a: 1}
]
const sortFn = x => x.a

const result = R.sortBy(sortFn, list)
const expected = [
  {a: 1},
  {a: 2},
  {a: 3}
]
// => `result` is equal to `expected`

Try this R.sortBy example in Rambda REPL

All Typescript definitions
sortBy<T>(sortFn: (a: T) => Ord, list: readonly T[]): readonly T[];
sortBy(sortFn: (a: any) => Ord): <T>(list: readonly T[]) => readonly T[];
R.sortBy source
export function sortBy(sortFn, list){
  if (arguments.length === 1) return _list => sortBy(sortFn, _list)

  const clone = list.slice()

  return clone.sort((a, b) => {
    const aSortResult = sortFn(a)
    const bSortResult = sortFn(b)

    if (aSortResult === bSortResult) return 0

    return aSortResult < bSortResult ? -1 : 1
  })
}
Tests
import { compose } from './compose'
import { prop } from './prop'
import { sortBy } from './sortBy'
import { toLower } from './toLower'

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

  const result = sortBy(x => x.a)(input)
  expect(result).toEqual(expected)
})

test('with compose', () => {
  const alice = {
    name : 'ALICE',
    age  : 101,
  }
  const bob = {
    name : 'Bob',
    age  : -10,
  }
  const clara = {
    name : 'clara',
    age  : 314.159,
  }
  const people = [ clara, bob, alice ]
  const sortByNameCaseInsensitive = sortBy(compose(toLower, prop('name')))

  expect(sortByNameCaseInsensitive(people)).toEqual([ alice, bob, clara ])
})
Typescript test
import {sortBy} from 'rambda'

interface Input {
  a: number,
}

describe('R.sortBy', () => {
  it('passing type to sort function', () => {
    function fn(x: any): number {
      return x.a
    }
    function fn2(x: Input): number {
      return x.a
    }

    const input = [{a: 2}, {a: 1}, {a: 0}]
    const result = sortBy(fn, input)
    const curriedResult = sortBy(fn2)(input)

    result // $ExpectType { a: number; }[]
    curriedResult // $ExpectType { a: number; }[]
    result[0].a // $ExpectType number
  })
  it('passing type to sort function and list', () => {
    function fn(x: Input): number {
      return x.a
    }

    const input: Input[] = [{a: 2}, {a: 1}, {a: 0}]
    const result = sortBy(fn, input)
    const curriedResult = sortBy(fn)(input)

    result // $ExpectType Input[]
    curriedResult // $ExpectType Input[]
    result[0].a // $ExpectType number
  })
})
Rambda is fastest. Ramda is 61.57% slower and Lodash is 88.88% slower
const R = require('../../dist/rambda.js')

const list = [ { a : 2 }, { a : 1 }, { a : 0 } ]
const fn = x => x.a

const replace = [
  {
    label : 'Rambda',
    fn    : () => {
      R.sortBy(fn, list)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.sortBy(fn, list)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.sortBy(list, fn)
    },
  },
]

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

split

split(separator: string | RegExp): (str: string) => readonly string[]

Curried version of String.prototype.split

const str = 'foo|bar|baz'
const separator = |'
const result = R.split(separator, str))
// => [ 'foo', 'bar', 'baz' ]

Try this R.split example in Rambda REPL

All Typescript definitions
split(separator: string | RegExp): (str: string) => readonly string[];
split(separator: string | RegExp, str: string): readonly string[];
R.split source
export function split(separator, str){
  if (arguments.length === 1) return _str => split(separator, _str)

  return str.split(separator)
}
Tests
import { split } from './split'

const str = 'foo|bar|baz'
const splitChar = '|'
const expected = [ 'foo', 'bar', 'baz' ]

test('happy', () => {
  expect(split(splitChar, str)).toEqual(expected)
})

test('curried', () => {
  expect(split(splitChar)(str)).toEqual(expected)
})
Typescript test
import {split} from 'rambda'

const str = 'foo|bar|baz'
const splitChar = '|'

describe('R.split', () => {
  it('happy', () => {
    const result = split(splitChar, str)

    result // $ExpectType string[]
  })
  it('curried', () => {
    const result = split(splitChar)(str)

    result // $ExpectType string[]
  })
})
Rambda is fastest. Ramda is 85.34% slower and Lodash is 33.69% slower
const R = require('../../dist/rambda.js')

const str = 'foo|bar|baz'
const sep = '|'

const split = [
  {
    label : 'Rambda',
    fn    : () => {
      R.split(sep, str)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.split(sep, str)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.split(str, sep)
    },
  },
]

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

splitAt

splitAt<T>(index: number, input: readonly T[]): readonly [readonly T[], readonly T[]]

It splits string or array at a given index.

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

Try this R.splitAt example in Rambda REPL

All Typescript definitions
splitAt<T>(index: number, input: readonly T[]): readonly [readonly T[], readonly T[]];
splitAt(index: number, input: string): readonly [string, string];
splitAt(index: number): {
    <T>(input: readonly T[]): readonly [readonly T[], readonly T[]];
    (input: string): readonly [string, string];
};
R.splitAt source
import { _isArray } from './_internals/_isArray'
import { drop } from './drop'
import { maybe } from './maybe'
import { take } from './take'

export function splitAt(index, input){
  if (arguments.length === 1){
    return _list => splitAt(index, _list)
  }
  if (!input) throw new TypeError(`Cannot read property 'slice' of ${ input }`)

  if (!_isArray(input) && typeof input !== 'string') return [ [], [] ]

  const correctIndex = maybe(
    index < 0,
    input.length + index < 0 ? 0 : input.length + index,
    index
  )

  return [ take(correctIndex, input), drop(correctIndex, input) ]
}
Tests
import { splitAt as splitAtRamda } from 'ramda'

import { splitAt } from './splitAt'

const list = [ 1, 2, 3 ]
const str = 'foo bar'

test('with array', () => {
  const result = splitAt(2, list)
  expect(result).toEqual([ [ 1, 2 ], [ 3 ] ])
})

test('with array - index is negative number', () => {
  const result = splitAt(-6, list)
  expect(result).toEqual([ [], list ])
})

test('with array - index is out of scope', () => {
  const result = splitAt(4, list)
  expect(result).toEqual([ [ 1, 2, 3 ], [] ])
})

test('with string', () => {
  const result = splitAt(4, str)
  expect(result).toEqual([ 'foo ', 'bar' ])
})

test('with string - index is negative number', () => {
  const result = splitAt(-2, str)
  expect(result).toEqual([ 'foo b', 'ar' ])
})

test('with string - index is out of scope', () => {
  const result = splitAt(10, str)
  expect(result).toEqual([ str, '' ])
})

test('with array - index is out of scope', () => {
  const result = splitAt(4)(list)
  expect(result).toEqual([ [ 1, 2, 3 ], [] ])
})

const badInputs = [ 1, true, /foo/g, {} ]
const throwingBadInputs = [ null, undefined ]

test('with bad inputs', () => {
  throwingBadInputs.forEach(badInput => {
    expect(() => splitAt(1, badInput)).toThrowWithMessage(TypeError,
      `Cannot read property 'slice' of ${ badInput }`)
    expect(() => splitAtRamda(1, badInput)).toThrowWithMessage(TypeError,
      `Cannot read property 'slice' of ${ badInput }`)
  })

  badInputs.forEach(badInput => {
    const result = splitAt(1, badInput)
    const ramdaResult = splitAtRamda(1, badInput)
    expect(result).toEqual(ramdaResult)
  })
})
Typescript test
import {splitAt} from 'ramda'

const index = 1
const str = 'foo'
const list = [1, 2, 3]

describe('R.splitAt with array', () => {
  it('happy', () => {
    const result = splitAt(index, list)

    result // $ExpectType [number[], number[]]
  })
  it('curried', () => {
    const result = splitAt(index)(list)

    result // $ExpectType [number[], number[]]
  })
})

describe('R.splitAt with string', () => {
  it('happy', () => {
    const result = splitAt(index, str)

    result // $ExpectType [string, string]
  })
  it('curried', () => {
    const result = splitAt(index)(str)

    result // $ExpectType [string, string]
  })
})

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

splitEvery

splitEvery<T>(sliceLength: number, input: readonly T[]): readonly (readonly T[])[]

It splits input into slices of sliceLength.

const result = [
  R.splitEvery(2, [1, 2, 3]), 
  R.splitEvery(3, 'foobar') 
]

const expected = [
  [[1, 2], [3]],
  ['foo', 'bar']
]
// => `result` is equal to `expected`

Try this R.splitEvery example in Rambda REPL

All Typescript definitions
splitEvery<T>(sliceLength: number, input: readonly T[]): readonly (readonly T[])[];
splitEvery(sliceLength: number, input: string): readonly string[];
splitEvery(sliceLength: number): {
  (input: string): readonly string[];
  <T>(input: readonly T[]): readonly (readonly T[])[];
};
R.splitEvery source
export function splitEvery(sliceLength, listOrString){
  if (arguments.length === 1){
    return _listOrString => splitEvery(sliceLength, _listOrString)
  }

  if (sliceLength < 1){
    throw new Error('First argument to splitEvery must be a positive integer')
  }

  const willReturn = []
  let counter = 0

  while (counter < listOrString.length){
    willReturn.push(listOrString.slice(counter, counter += sliceLength))
  }

  return willReturn
}
Tests
import { splitEvery } from './splitEvery'

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

  expect(splitEvery(3)('foobarbaz')).toEqual([ 'foo', 'bar', 'baz' ])
})

test('with bad input', () => {
  expect(() =>
    expect(splitEvery(0)('foo')).toEqual([ 'f', 'o', 'o' ])).toThrowWithMessage(Error,
    'First argument to splitEvery must be a positive integer')
})
Typescript test
import {splitEvery} from 'rambda'

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

describe('R.splitEvery', () => {
  it('happy', () => {
    const result = splitEvery(3, list)

    result // $ExpectType (number[])[]
  })
  it('curried', () => {
    const result = splitEvery(3)(list)

    result // $ExpectType (number[])[]
  })
})
Rambda is faster than Ramda with 90.18%
const R = require('../../dist/rambda.js')

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

const splitEvery = [
  {
    label : 'Rambda',
    fn    : () => {
      R.splitEvery(3, list)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.splitEvery(3, list)
    },
  },
]

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

splitWhen

splitWhen<T, U>(predicate: Predicate<T>, list: readonly U[]): readonly (readonly U[])[]

It splits list to two arrays according to a predicate function.

The first array contains all members of list before predicate returns true.

const list = [1, 2, 1, 2]
const result = R.splitWhen(R.equals(2), list)
// => [[1], [2, 1, 2]]

Try this R.splitWhen example in Rambda REPL

All Typescript definitions
splitWhen<T, U>(predicate: Predicate<T>, list: readonly U[]): readonly (readonly U[])[];
splitWhen<T>(predicate: Predicate<T>): <U>(list: readonly U[]) => readonly (readonly U[])[];
R.splitWhen source
export function splitWhen(predicate, input){
  if (arguments.length === 1){
    return _input => splitWhen(predicate, _input)
  }
  if (!input)
    throw new TypeError(`Cannot read property 'length' of ${ input }`)

  const preFound = []
  const postFound = []
  let found = false
  let counter = -1

  while (counter++ < input.length - 1){
    if (found){
      postFound.push(input[ counter ])
    } else if (predicate(input[ counter ])){
      postFound.push(input[ counter ])
      found = true
    } else {
      preFound.push(input[ counter ])
    }
  }

  return [ preFound, postFound ]
}
Tests
import { splitWhen as splitWhenRamda } from 'ramda'

import { equals } from './equals'
import { splitWhen } from './splitWhen'

const list = [ 1, 2, 1, 2 ]

test('happy', () => {
  const result = splitWhen(equals(2), list)
  expect(result).toEqual([ [ 1 ], [ 2, 1, 2 ] ])
})

test('when predicate returns false', () => {
  const result = splitWhen(equals(3))(list)
  expect(result).toEqual([ list, [] ])
})

const badInputs = [ 1, true, /foo/g, {} ]
const throwingBadInputs = [ null, undefined ]

test('with bad inputs', () => {
  throwingBadInputs.forEach(badInput => {
    expect(() => splitWhen(equals(2), badInput)).toThrowWithMessage(TypeError,
      `Cannot read property 'length' of ${ badInput }`)
    expect(() => splitWhenRamda(equals(2), badInput)).toThrowWithMessage(TypeError,
      `Cannot read property 'length' of ${ badInput }`)
  })

  badInputs.forEach(badInput => {
    const result = splitWhen(equals(2), badInput)
    const ramdaResult = splitWhenRamda(equals(2), badInput)
    expect(result).toEqual(ramdaResult)
  })
})
Typescript test
import {splitWhen} from 'rambda'

const list = [1, 2, 1, 2]
const predicate = (x: number) => x === 2

describe('R.splitWhen', () => {
  it('happy', () => {
    const result = splitWhen(predicate, list)

    result // $ExpectType (number[])[]
  })
  it('curried', () => {
    const result = splitWhen(predicate)(list)

    result // $ExpectType (number[])[]
  })
})

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

startsWith

startsWith(target: string, str: string): boolean

Curried version of String.prototype.startsWith

💥 It doesn't work with arrays unlike its corresponding Ramda method.

const str = 'foo-bar'

const result = [
  R.startsWith('foo', str),
  R.startsWith('bar', str)
]
// => [true, false]

Try this R.startsWith example in Rambda REPL

All Typescript definitions
startsWith(target: string, str: string): boolean;
startsWith(target: string): (str: string) => boolean;
R.startsWith source
export function startsWith(target, str){
  if (arguments.length === 1) return _str => startsWith(target, _str)

  return str.startsWith(target)
}
Tests
import { startsWith } from './startsWith'

test('true', () => {
  const result = startsWith('foo', 'foo-bar')

  expect(result).toBeTrue()
})

test('false', () => {
  const result = startsWith('baz')('foo-bar')

  expect(result).toBeFalse()
})
Typescript test
import {startsWith} from 'rambda'

const target = 'foo'
const input = 'foo bar'

describe('R.startsWith', () => {
  it('happy', () => {
    const result = startsWith(target, input)

    result // $ExpectType boolean
  })
  it('curried', () => {
    const result = startsWith(target)(input)

    result // $ExpectType boolean
  })
})

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

subtract

Curried version of x - y

const x = 3
const y = 1

R.subtract(x, y) 
// => 2

Try this R.subtract example in Rambda REPL

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

sum

sum(list: readonly number[]): number
R.sum([1, 2, 3, 4, 5]) 
// => 15

Try this R.sum example in Rambda REPL

All Typescript definitions
sum(list: readonly number[]): number;
R.sum source
export function sum(list){
  return list.reduce((prev, current) => prev + current, 0)
}
Tests
import { sum } from './sum'

test('happy', () => {
  expect(sum([ 1, 2, 3, 4, 5 ])).toBe(15)
})

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

symmetricDifference

symmetricDifference<T>(x: readonly T[], y: readonly T[]): readonly T[]

It returns a merged list of x and y with all equal elements removed.

R.equals is used to determine equality.

const x = [ 1, 2, 3, 4 ]
const y = [ 3, 4, 5, 6 ]

const result = symmetricDifference(x, y)
// => [ 1, 2, 5, 6 ]

Try this R.symmetricDifference example in Rambda REPL

All Typescript definitions
symmetricDifference<T>(x: readonly T[], y: readonly T[]): readonly T[];
symmetricDifference<T>(x: readonly T[]): <T>(y: readonly T[]) => readonly T[];
R.symmetricDifference source
import { concat } from './concat'
import { filter } from './filter'
import { includes } from './includes'

export function symmetricDifference(x, y){
  if (arguments.length === 1){
    return _y => symmetricDifference(x, _y)
  }

  return concat(filter(value => !includes(value, y), x),
    filter(value => !includes(value, x), y))
}
Tests
import { symmetricDifference } from './symmetricDifference'

test('symmetricDifference', () => {
  const list1 = [ 1, 2, 3, 4 ]
  const list2 = [ 3, 4, 5, 6 ]
  expect(symmetricDifference(list1)(list2)).toEqual([ 1, 2, 5, 6 ])

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

test('symmetricDifference with objects', () => {
  const list1 = [ { id : 1 }, { id : 2 }, { id : 3 }, { id : 4 } ]
  const list2 = [ { id : 3 }, { id : 4 }, { id : 5 }, { id : 6 } ]
  expect(symmetricDifference(list1)(list2)).toEqual([
    { id : 1 },
    { id : 2 },
    { id : 5 },
    { id : 6 },
  ])
})
Typescript test
import {symmetricDifference} from 'rambda'

describe('R.symmetricDifference', () => {
  it('happy', () => {
    const list1 = [1, 2, 3, 4]
    const list2 = [3, 4, 5, 6]
    const result = symmetricDifference(list1, list2)

    result // $ExpectType number[]
  })

  it('curried', () => {
    const list1 = [{id: 1}, {id: 2}, {id: 3}, {id: 4}]
    const list2 = [{id: 3}, {id: 4}, {id: 5}, {id: 6}]
    const result = symmetricDifference(list1)(list2)

    result // $ExpectType { id: number; }[]
  })
})

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

T

T(): boolean
R.T() 
// => true

Try this R.T example in Rambda REPL

All Typescript definitions
T(): boolean;
R.T source
export function T(){
  return true
}

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

tail

tail<T>(input: readonly T[]): readonly T[]

It returns all but the first element of input.

const result = [
  R.tail([1, 2, 3]),  
  R.tail('foo') 
]
// => [[2, 3], 'oo']

Try this R.tail example in Rambda REPL

All Typescript definitions
tail<T>(input: readonly T[]): readonly T[];
tail(input: string): string;
R.tail source
import { drop } from './drop'

export function tail(listOrString){
  return drop(1, listOrString)
}
Tests
import { tail } from './tail'

test('tail', () => {
  expect(tail([ 1, 2, 3 ])).toEqual([ 2, 3 ])
  expect(tail([ 1, 2 ])).toEqual([ 2 ])
  expect(tail([ 1 ])).toEqual([])
  expect(tail([])).toEqual([])

  expect(tail('abc')).toEqual('bc')
  expect(tail('ab')).toEqual('b')
  expect(tail('a')).toEqual('')
  expect(tail('')).toEqual('')
})
Typescript test
import {tail} from 'rambda'

describe('R.tail', () => {
  it('with string', () => {
    const result = tail('foo')

    result // $ExpectType string
  })
  it('with list', () => {
    const result = tail([1, 2, 3])

    result // $ExpectType number[]
  })
})

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

take

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

It returns the first howMany elements of input.

const howMany = 2

const result = [
  R.take(howMany, [1, 2, 3]),
  R.take(howMany, 'foobar'),
]
// => [[1, 2], 'fo']

Try this R.take example in Rambda REPL

All Typescript definitions
take<T>(howMany: number, input: readonly T[]): readonly T[];
take(howMany: number, input: string): string;
take<T>(howMany: number): {
  <T>(input: readonly T[]): readonly T[];
  (input: string): string;
};
R.take source
import baseSlice from './_internals/baseSlice'

export function take(howMany, listOrString){
  if (arguments.length === 1)
    return _listOrString => take(howMany, _listOrString)
  if (howMany < 0) return listOrString.slice()
  if (typeof listOrString === 'string') return listOrString.slice(0, howMany)

  return baseSlice(
    listOrString, 0, howMany
  )
}
Tests
import { take } from './take'

test('happy', () => {
  const arr = [ 'foo', 'bar', 'baz' ]

  expect(take(1, arr)).toEqual([ 'foo' ])

  expect(arr).toEqual([ 'foo', 'bar', 'baz' ])

  expect(take(2)([ 'foo', 'bar', 'baz' ])).toEqual([ 'foo', 'bar' ])
  expect(take(3, [ 'foo', 'bar', 'baz' ])).toEqual([ 'foo', 'bar', 'baz' ])
  expect(take(4, [ 'foo', 'bar', 'baz' ])).toEqual([ 'foo', 'bar', 'baz' ])
  expect(take(3)('rambda')).toEqual('ram')
})

test('with negative index', () => {
  expect(take(-1, [ 1, 2, 3 ])).toEqual([ 1, 2, 3 ])
  expect(take(-Infinity, [ 1, 2, 3 ])).toEqual([ 1, 2, 3 ])
})

test('with zero index', () => {
  expect(take(0, [ 1, 2, 3 ])).toEqual([])
})
Typescript test
import {take} from 'rambda'

const list = [1, 2, 3, 4]
const str = 'foobar'
const howMany = 2

describe('R.take - array', () => {
  it('happy', () => {
    const result = take(howMany, list)

    result // $ExpectType number[]
  })
  it('curried', () => {
    const result = take(howMany)(list)

    result // $ExpectType number[]
  })
})

describe('R.take - string', () => {
  it('happy', () => {
    const result = take(howMany, str)

    result // $ExpectType string
  })
  it('curried', () => {
    const result = take(howMany)(str)

    result // $ExpectType string
  })
})
Lodash is fastest. Rambda is 93.44% slower and Ramda is 98.04% slower
const R = require('../../dist/rambda.js')

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

const take = [
  {
    label : 'Rambda',
    fn    : () => {
      R.take(num, list)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.take(num, list)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.take(list, num)
    },
  },
]

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

takeLast

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

It returns the last howMany elements of input.

const howMany = 2

const result = [
  R.takeLast(howMany, [1, 2, 3]),
  R.takeLast(howMany, 'foobar'),
]
// => [[2, 3], 'ar']

Try this R.takeLast example in Rambda REPL

All Typescript definitions
takeLast<T>(howMany: number, input: readonly T[]): readonly T[];
takeLast(howMany: number, input: string): string;
takeLast<T>(howMany: number): {
  <T>(input: readonly T[]): readonly T[];
  (input: string): string;
};
R.takeLast source
import baseSlice from './_internals/baseSlice'

export function takeLast(howMany, listOrString){
  if (arguments.length === 1)
    return _listOrString => takeLast(howMany, _listOrString)

  const len = listOrString.length
  if (howMany < 0) return listOrString.slice()
  let numValue = howMany > len ? len : howMany

  if (typeof listOrString === 'string')
    return listOrString.slice(len - numValue)

  numValue = len - numValue

  return baseSlice(
    listOrString, numValue, len
  )
}
Tests
import { takeLast } from './takeLast'

test('with arrays', () => {
  expect(takeLast(1, [ 'foo', 'bar', 'baz' ])).toEqual([ 'baz' ])

  expect(takeLast(2)([ 'foo', 'bar', 'baz' ])).toEqual([ 'bar', 'baz' ])

  expect(takeLast(3, [ 'foo', 'bar', 'baz' ])).toEqual([ 'foo', 'bar', 'baz' ])

  expect(takeLast(4, [ 'foo', 'bar', 'baz' ])).toEqual([ 'foo', 'bar', 'baz' ])

  expect(takeLast(10, [ 'foo', 'bar', 'baz' ])).toEqual([ 'foo', 'bar', 'baz' ])
})

test('with strings', () => {
  expect(takeLast(3, 'rambda')).toEqual('bda')

  expect(takeLast(7, 'rambda')).toEqual('rambda')
})

test('with negative index', () => {
  expect(takeLast(-1, [ 1, 2, 3 ])).toEqual([ 1, 2, 3 ])
  expect(takeLast(-Infinity, [ 1, 2, 3 ])).toEqual([ 1, 2, 3 ])
})
Typescript test
import {takeLast} from 'rambda'

const list = [1, 2, 3, 4]
const str = 'foobar'
const howMany = 2

describe('R.takeLast - array', () => {
  it('happy', () => {
    const result = takeLast(howMany, list)

    result // $ExpectType number[]
  })
  it('curried', () => {
    const result = takeLast(howMany)(list)

    result // $ExpectType number[]
  })
})

describe('R.takeLast - string', () => {
  it('happy', () => {
    const result = takeLast(howMany, str)

    result // $ExpectType string
  })
  it('curried', () => {
    const result = takeLast(howMany)(str)

    result // $ExpectType string
  })
})
Lodash is fastest. Rambda is 92.61% slower and Ramda is 98.83% slower
const R = require('../../dist/rambda.js')

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

const takeLast = [
  {
    label : 'Rambda',
    fn    : () => {
      R.takeLast(num, list)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.takeLast(num, list)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.takeRight(list, num)
    },
  },
]

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

takeLastWhile

takeLastWhile(predicate: (x: string) => boolean, input: string): string
const result = R.takeLastWhile(
  x => x > 2,
  [1, 2, 3, 4]
)
// => [3, 4]

Try this R.takeLastWhile example in Rambda REPL

All Typescript definitions
takeLastWhile(predicate: (x: string) => boolean, input: string): string;
takeLastWhile(predicate: (x: string) => boolean): (input: string) => string;
takeLastWhile<T>(predicate: (x: T) => boolean, input: readonly T[]): readonly T[];
takeLastWhile<T>(predicate: (x: T) => boolean): <T>(input: readonly T[]) => readonly T[];
R.takeLastWhile source
import { _isArray } from './_internals/_isArray'

export function takeLastWhile(predicate, input){
  if (arguments.length === 1){
    return _input => takeLastWhile(predicate, _input)
  }
  if (input.length === 0) return input
  let found = false
  const toReturn = []
  let counter = input.length

  while (!found || counter === 0){
    counter--
    if (predicate(input[ counter ]) === false){
      found = true
    } else if (!found){
      toReturn.push(input[ counter ])
    }
  }

  return _isArray(input) ? toReturn.reverse() : toReturn.reverse().join('')
}
Tests
import { takeLastWhile } from './takeLastWhile'
const assert = require('assert')

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

test('happy', () => {
  const predicate = x => x > 2
  const result = takeLastWhile(predicate, list)
  expect(result).toEqual([ 3, 4 ])
})

test('predicate is always true', () => {
  const predicate = x => x > 0
  const result = takeLastWhile(predicate)(list)
  expect(result).toEqual(list)
})

test('predicate is always false', () => {
  const predicate = x => x < 0
  const result = takeLastWhile(predicate, list)
  expect(result).toEqual([])
})

test('with string', () => {
  const result = takeLastWhile(x => x !== 'F', 'FOOBAR')
  expect(result).toEqual('OOBAR')
})
Typescript test
import {takeLastWhile} from 'rambda'

const list = [1, 2, 3]
const str = 'FOO'

describe('R.takeLastWhile', () => {
  it('with array', () => {
    const result = takeLastWhile(x => x > 1, list)

    result // $ExpectType number[]
  })
  it('with array - curried', () => {
    const result = takeLastWhile(x => x > 1, list)

    result // $ExpectType number[]
  })
  it('with string', () => {
    const result = takeLastWhile(x => x !== 'F', str)

    result // $ExpectType string
  })
  it('with string - curried', () => {
    const result = takeLastWhile(x => x !== 'F')(str)

    result // $ExpectType string
  })
})

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

takeWhile

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

const result = R.takeWhile(predicate, list)
// => [1, 2]

Try this R.takeWhile example in Rambda REPL

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

tap

tap<T>(fn: (x: T) => void, input: T): T

It applies function fn to input x and returns x.

One use case is debuging in the middle of R.compose.

const list = [1, 2, 3]

R.compose(
  R.map(x => x * 2)
  R.tap(console.log),
  R.filter(x => x > 1)
)(list)
// => `2` and `3` will be logged

Try this R.tap example in Rambda REPL

All Typescript definitions
tap<T>(fn: (x: T) => void, input: T): T;
tap<T>(fn: (x: T) => void): (input: T) => T;
R.tap source
export function tap(fn, x){
  if (arguments.length === 1) return _x => tap(fn, _x)

  fn(x)

  return x
}
Tests
import { tap } from './tap'

test('tap', () => {
  let a = 1
  const sayX = x => a = x

  expect(tap(sayX, 100)).toEqual(100)
  expect(tap(sayX)(100)).toEqual(100)
  expect(a).toEqual(100)
})
Typescript test
import {tap, pipe} from 'rambda'

describe('R.tap', () => {
  it('happy', () => {
    pipe(
      tap(x => {
        x // $ExpectType number[]
      }),
      (x: number[]) => x.length
    )([1, 2])
  })
})

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

test

test(regExpression: RegExp): (str: string) => boolean

It determines whether str matches regExpression.

R.test(/^f/, 'foo')
// => true

Try this R.test example in Rambda REPL

All Typescript definitions
test(regExpression: RegExp): (str: string) => boolean;
test(regExpression: RegExp, str: string): boolean;
R.test source
export function test(pattern, str){
  if (arguments.length === 1) return _str => test(pattern, _str)

  if (typeof pattern === 'string'){
    throw new TypeError(`‘test’ requires a value of type RegExp as its first argument; received "${ pattern }"`)
  }

  return str.search(pattern) !== -1
}
Tests
import { test as testMethod } from './test'

test('happy', () => {
  expect(testMethod(/^x/, 'xyz')).toBeTrue()

  expect(testMethod(/^y/)('xyz')).toBeFalse()
})

test('throws if first argument is not regex', () => {
  expect(() => testMethod('foo', 'bar')).toThrowWithMessage(TypeError,
    '‘test’ requires a value of type RegExp as its first argument; received "foo"')
})
Typescript test
import {test} from 'rambda'

const input = 'foo   '
const regex = /foo/

describe('R.test', () => {
  it('happy', () => {
    const result = test(regex, input)

    result // $ExpectType boolean
  })
  it('curried', () => {
    const result = test(regex)(input)

    result // $ExpectType boolean
  })
})
Rambda is faster than Ramda with 94.42%
const R = require('../../dist/rambda.js')

const test = [
  {
    label : 'Rambda',
    fn    : () => {
      R.test(/\s/g, 'x y z')
      R.test(/\s/g)('x y z')
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.test(/\s/g, 'x y z')
      Ramda.test(/\s/g)('x y z')
    },
  },
]

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

times

times<T>(fn: (i: number) => T, howMany: number): readonly T[]

It returns the result of applying function fn over members of range array.

The range array includes numbers between 0 and howMany(exclusive).

const fn = x => x * 2
const howMany = 5

R.times(fn, howMany)
// => [0, 2, 4, 6, 8]

Try this R.times example in Rambda REPL

All Typescript definitions
times<T>(fn: (i: number) => T, howMany: number): readonly T[];
times<T>(fn: (i: number) => T): (howMany: number) => readonly T[];
R.times source
import { map } from './map'
import { range } from './range'

export function times(fn, howMany){
  if (arguments.length === 1) return _howMany => times(fn, _howMany)
  if (!Number.isInteger(howMany) || howMany < 0){
    throw new RangeError('n must be an integer')
  }

  return map(fn, range(0, howMany))
}
Tests
import assert from 'assert'

import { identity } from './identity'
import { times } from './times'

test('happy', () => {
  const result = times(identity, 5)

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

test('with bad input', () => {
  assert.throws(() => {
    times(3)('cheers!')
  }, RangeError)
  assert.throws(() => {
    times(identity, -1)
  }, RangeError)
})

test('curry', () => {
  const result = times(identity)(5)

  expect(result).toEqual([ 0, 1, 2, 3, 4 ])
})
Typescript test
import {times, identity} from 'rambda'

describe('R.times', () => {
  it('happy', () => {
    const result = times(identity, 5)
    result // $ExpectType number[]
  })
})

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

toLower

toLower(str: string): string
R.toLower('FOO')
// => 'foo'

Try this R.toLower example in Rambda REPL

All Typescript definitions
toLower(str: string): string;
R.toLower source
export function toLower(str){
  return str.toLowerCase()
}
Tests
import { toLower } from './toLower'

test('toLower', () => {
  expect(toLower('FOO|BAR|BAZ')).toEqual('foo|bar|baz')
})

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

toPairs

toPairs<S>(obj: { readonly [k: string]: S } | { readonly [k: number]: S }): readonly (readonly [string, S])[]

It transforms an object to a list.

const list = {
  a : 1,
  b : 2,
  c : [ 3, 4 ],
}
const expected = [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', [ 3, 4 ] ] ]

const result = R.toPairs(list)
// => `result` is equal to `expected`

Try this R.toPairs example in Rambda REPL

All Typescript definitions
toPairs<S>(obj: { readonly [k: string]: S } | { readonly [k: number]: S }): readonly (readonly [string, S])[];
R.toPairs source
export function toPairs(obj){
  return Object.entries(obj)
}
Tests
import { toPairs } from './toPairs'

const obj = {
  a : 1,
  b : 2,
  c : [ 3, 4 ],
}
const expected = [
  [ 'a', 1 ],
  [ 'b', 2 ],
  [ 'c', [ 3, 4 ] ],
]

test('happy', () => {
  expect(toPairs(obj)).toEqual(expected)
})
Typescript test
import {toPairs} from 'rambda'

const obj = {
  a: 1,
  b: 2,
  c: [3, 4],
}

describe('R.toPairs', () => {
  it('happy', () => {
    const result = toPairs(obj)

    result // $ExpectType ([string, number | number[]])[]
  })
})

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

toString

toString<T>(x: T): string
R.toString([1, 2]) 
// => '1,2'

Try this R.toString example in Rambda REPL

All Typescript definitions
toString<T>(x: T): string;
R.toString source
export function toString(x){
  return x.toString()
}
Tests
import { toString } from './toString'

test('happy', () => {
  expect(toString([ 1, 2, 3 ])).toEqual('1,2,3')
})

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

toUpper

toUpper(str: string): string
R.toUpper('foo')
// => 'FOO'

Try this R.toUpper example in Rambda REPL

All Typescript definitions
toUpper(str: string): string;
R.toUpper source
export function toUpper(str){
  return str.toUpperCase()
}
Tests
import { toUpper } from './toUpper'

test('toUpper', () => {
  expect(toUpper('foo|bar|baz')).toEqual('FOO|BAR|BAZ')
})

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

transpose

transpose<T>(list: readonly (readonly T[])[]): readonly (readonly T[])[]
const list = [[10, 11], [20], [], [30, 31, 32]]
const expected = [[10, 20, 30], [11, 31], [32]]

const result = R.transpose(list)
// => `result` is equal to `expected`

Try this R.transpose example in Rambda REPL

All Typescript definitions
transpose<T>(list: readonly (readonly T[])[]): readonly (readonly T[])[];
R.transpose source
import { _isArray } from './_internals/_isArray'

export function transpose(array){
  return array.reduce((acc, el) => {
    el.forEach((nestedEl, i) =>
      _isArray(acc[ i ]) ? acc[ i ].push(nestedEl) : acc.push([ nestedEl ]))

    return acc
  }, [])
}
Tests
import { transpose } from './transpose'

test('happy', () => {
  const input = [
    [ 'a', 1 ],
    [ 'b', 2 ],
    [ 'c', 3 ],
  ]

  expect(transpose(input)).toEqual([
    [ 'a', 'b', 'c' ],
    [ 1, 2, 3 ],
  ])
})

test('when rows are shorter', () => {
  const actual = transpose([ [ 10, 11 ], [ 20 ], [], [ 30, 31, 32 ] ])
  const expected = [ [ 10, 20, 30 ], [ 11, 31 ], [ 32 ] ]
  expect(actual).toEqual(expected)
})

test('with empty array', () => {
  expect(transpose([])).toEqual([])
})

test('array with falsy values', () => {
  const actual = transpose([
    [ true, false, undefined, null ],
    [ null, undefined, false, true ],
  ])
  const expected = [
    [ true, null ],
    [ false, undefined ],
    [ undefined, false ],
    [ null, true ],
  ]
  expect(actual).toEqual(expected)
})
Typescript test
import {transpose} from 'rambda'

const input = [
  ['a', 1],
  ['b', 2],
  ['c', 3],
]

describe('R.transpose', () => {
  it('happy', () => {
    const result = transpose(input)

    result // $ExpectType ((string | number)[])[]
  })
})

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

trim

trim(str: string): string
R.trim('  foo  ') 
// => 'foo'

Try this R.trim example in Rambda REPL

All Typescript definitions
trim(str: string): string;
R.trim source
export function trim(str){
  return str.trim()
}
Tests
import { trim } from './trim'

test('trim', () => {
  expect(trim(' foo ')).toEqual('foo')
})

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

tryCatch

tryCatch<T, U>(
  fn: (input: T) => U,
  fallback: U
): (input: T) => U

It returns function that runs fn in try/catch block. If there was an error, then fallback is used to return the result. Note that fn can be value or asynchronous/synchronous function(unlike Ramda where fallback can only be a synchronous function).

💥 Please check the tests of R.tryCatch to fully understand how this method works.

const fn = x => x.foo

const result = [
  R.tryCatch(fn, false)(null),
  R.tryCatch(fn, false)({foo: 'bar'})
]
// => [false, 'bar']

Try this R.tryCatch example in Rambda REPL

All Typescript definitions
tryCatch<T, U>(
  fn: (input: T) => U,
  fallback: U
): (input: T) => U;
tryCatch<T, U>(
  fn: (input: T) => U,
  fallback: (input: T) => U
): (input: T) => U;
tryCatch<T>(
  fn: (input: any) => Promise<any>,
  fallback: T
): (input: any) => Promise<T>;
tryCatch<T>(
  fn: (input: any) => Promise<any>,
  fallback: (input: any) => Promise<any>,
): (input: any) => Promise<T>;
R.tryCatch source
import { isFunction } from './isFunction'

export function tryCatch(fn, fallback){
  if (!isFunction(fn)){
    throw new Error(`R.tryCatch | fn '${ fn }'`)
  }
  const passFallback = isFunction(fallback)

  return (...inputs) => {
    try {
      return fn(...inputs)
    } catch (e){
      return passFallback ? fallback(e, ...inputs) : fallback
    }
  }
}
Tests
import { tryCatch as tryCatchRamda } from 'ramda'

import { compareCombinations } from './_internals/testUtils'
import { prop } from './prop'
import { tryCatch } from './tryCatch'

test('happy', () => {
  const fn = () => {
    throw new Error('foo')
  }
  const result = tryCatch(fn, () => true)()
  expect(result).toBeTrue()
})

test('when fallback is used', () => {
  const fn = x => x.x

  expect(tryCatch(fn, false)(null)).toBeFalse()
})

test('with json parse', () => {
  const good = () => JSON.parse(JSON.stringify({ a : 1 }))
  const bad = () => JSON.parse('a{a')

  expect(tryCatch(good, 1)()).toEqual({ a : 1 })
  expect(tryCatch(bad, 1)()).toBe(1)
})

test('when fallback is function', () => {
  const fn = x => x.x

  expect(tryCatch(fn, () => 1)(null)).toBe(1)
})

test('when fn is used', () => {
  const fn = prop('x')

  expect(tryCatch(fn, false)({})).toBe(undefined)
  expect(tryCatch(fn, false)({ x : 1 })).toBe(1)
})

test('fallback receives error object and all initial inputs', () => {
  function thrower(
    a, b, c
  ){
    void c
    throw new Error('throwerError')
  }

  function catchFn(
    e, a, b, c
  ){
    return [ e.message, a, b, c ].join('|')
  }

  const willThrow = tryCatch(thrower, catchFn)
  const result = willThrow(
    'A', 'B', 'C'
  )
  expect(result).toBe('throwerError|A|B|C')
})

test('fallback receives error object', () => {
  function throwFn(){
    throw new Error(10)
  }

  function eCatcher(
    e, a, b
  ){
    return e.message
  }

  const willThrow = tryCatch(throwFn, eCatcher)
  expect(willThrow([])).toBe('10')
  expect(willThrow([ {}, {}, {} ])).toBe('10')
})

const possibleFns = [
  null,
  () => 1,
  () => 0,
  () => JSON.parse('{a:1'),
  () => {
    const x = {}

    return x.x
  },
  x => x.foo,
  () => {
    throw new Error('foo')
  },
]

const possibleCatchers = [
  null,
  e => e.message.length,
  (e, ...inputs) => `${ e.message.length } ${ inputs.length }`,
  () => {
    throw new Error('bar')
  },
]

const possibleInputs = [ null, {}, { foo : 1 } ]

describe('brute force', () => {
  compareCombinations({
    returnsFunctionFlag : true,
    firstInput          : possibleFns,
    callback            : errorsCounters => {
      expect(errorsCounters).toMatchInlineSnapshot(`
        Object {
          "ERRORS_MESSAGE_MISMATCH": 0,
          "ERRORS_TYPE_MISMATCH": 12,
          "RESULTS_MISMATCH": 0,
          "SHOULD_NOT_THROW": 0,
          "SHOULD_THROW": 7,
        }
      `)
    },
    secondInput : possibleCatchers,
    thirdInput  : possibleInputs,
    fn          : tryCatch,
    fnRamda     : tryCatchRamda,
  })
})
Typescript test
import {tryCatch, delay} from 'rambda'

describe('R.tryCatch', () => {
  it('synchronous', () => {
    const fn = (x: any) => x.x === 1

    const result = tryCatch(fn, false)(null)
    result // $ExpectType boolean
  })
  it('synchronous + fallback is function', () => {
    const fn = (x: any) => typeof x.x
    const fallback = (x: any) => typeof x
    const result = tryCatch<any, string>(fn, fallback)(null)
    result // $ExpectType string
  })

  it('asynchronous', async() => {
    const fn = async(input: any) => {
      return typeof JSON.parse('{a:')
    }
    const result = await tryCatch<string>(fn, 'fallback')(100)
    result // $ExpectType string
  })

  it('asynchronous + fallback is asynchronous', async() => {
    const fn = async(input: any) => {
      await delay(100)
      return JSON.parse(`{a:${input}`)
    }
    const fallback = async(input: any) => {
      await delay(100)
      return 'foo'
    }
    const result = await tryCatch<string>(fn, fallback)(100)
    result // $ExpectType string
  })
})

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

type

type(x: any): RambdaTypes

It accepts any input and it returns its type.

💥 NaN, Promise and Async are types specific for Rambda.

R.type(() => {}) // => 'Function'
R.type(async () => {}) // => 'Async'
R.type([]) // => 'Array'
R.type({}) // => 'Object'
R.type('foo') // => 'String'
R.type(1) // => 'Number'
R.type(true) // => 'Boolean'
R.type(null) // => 'Null'
R.type(/[A-z]/) // => 'RegExp'
R.type('foo'*1) // => 'NaN'

const delay = ms => new Promise(resolve => {
  setTimeout(function () {
    resolve()
  }, ms)
})
R.type(delay) // => 'Promise'

Try this R.type example in Rambda REPL

All Typescript definitions
type(x: any): RambdaTypes;
R.type source
import { _isArray } from './_internals/_isArray'

export function type(input){
  const typeOf = typeof input

  if (input === null){
    return 'Null'
  } else if (input === undefined){
    return 'Undefined'
  } else if (typeOf === 'boolean'){
    return 'Boolean'
  } else if (typeOf === 'number'){
    return Number.isNaN(input) ? 'NaN' : 'Number'
  } else if (typeOf === 'string'){
    return 'String'
  } else if (_isArray(input)){
    return 'Array'
  } else if (typeOf === 'symbol'){
    return 'Symbol'
  } else if (input instanceof RegExp){
    return 'RegExp'
  }

  const asStr = input && input.toString ? input.toString() : ''

  if ([ 'true', 'false' ].includes(asStr)) return 'Boolean'
  if (!Number.isNaN(Number(asStr))) return 'Number'
  if (asStr.startsWith('async')) return 'Async'
  if (asStr === '[object Promise]') return 'Promise'
  if (typeOf === 'function') return 'Function'
  if (input instanceof String) return 'String'

  return 'Object'
}
Tests
import { type as ramdaType } from 'ramda'

import { type } from './type'

test('with symbol', () => {
  expect(type(Symbol())).toBe('Symbol')
})

test('with simple promise', () => {
  expect(type(Promise.resolve(1))).toBe('Promise')
})

test('with new Boolean', () => {
  expect(type(new Boolean(true))).toBe('Boolean')
})

test('with new String', () => {
  expect(type(new String('I am a String object'))).toEqual('String')
})

test('with new Number', () => {
  expect(type(new Number(1))).toBe('Number')
})

test('with new promise', () => {
  const delay = ms =>
    new Promise(resolve => {
      setTimeout(() => {
        resolve(ms + 110)
      }, ms)
    })

  expect(type(delay(10))).toEqual('Promise')
})

test('async function', () => {
  expect(type(async () => {})).toEqual('Async')
})

test('async arrow', () => {
  const asyncArrow = async () => {}
  expect(type(asyncArrow)).toBe('Async')
})

test('function', () => {
  const fn1 = () => {}
  const fn2 = function (){}

  function fn3(){}

  ;[ () => {}, fn1, fn2, fn3 ].map(val => {
    expect(type(val)).toEqual('Function')
  })
})

test('object', () => {
  expect(type({})).toEqual('Object')
})

test('number', () => {
  expect(type(1)).toEqual('Number')
})

test('boolean', () => {
  expect(type(false)).toEqual('Boolean')
})

test('string', () => {
  expect(type('foo')).toEqual('String')
})

test('null', () => {
  expect(type(null)).toEqual('Null')
})

test('array', () => {
  expect(type([])).toEqual('Array')
  expect(type([ 1, 2, 3 ])).toEqual('Array')
})

test('regex', () => {
  expect(type(/\s/g)).toEqual('RegExp')
})

test('undefined', () => {
  expect(type(undefined)).toEqual('Undefined')
})

test('not a number', () => {
  expect(type(Number('s'))).toBe('NaN')
})

test('function inside object 1', () => {
  const obj = {
    f(){
      return 4
    },
  }

  expect(type(obj.f)).toBe('Function')
  expect(ramdaType(obj.f)).toBe('Function')
})

test('function inside object 2', () => {
  const name = 'f'
  const obj = {
    [ name ](){
      return 4
    },
  }
  expect(type(obj.f)).toBe('Function')
  expect(ramdaType(obj.f)).toBe('Function')
})
Typescript test
import {type} from 'rambda'

describe('R.type', () => {
  it('happy', () => {
    const result = type(4)

    result // $ExpectType RambdaTypes
  })
})
Rambda is slower than Ramda with 18.91%
const R = require('../../dist/rambda.js')

const fn1 = () => {}
const fn2 = function (){}
function fn3(){}

const test = [
  {
    label : 'Rambda',
    fn    : () => {
      R.type(new Boolean(true))
      R.type(new String('I am a String object'))
      R.type(fn1)
      R.type(fn2)
      R.type(fn3)
      R.type(1)
      R.type({ a : 1 })
      R.type(null)
      R.type(undefined)
      R.type(Number('foo'))
      R.type([ 12, 3 ])
      R.type(/\s/g)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.type(new Boolean(true))
      Ramda.type(new String('I am a String object'))
      Ramda.type(fn1)
      Ramda.type(fn2)
      Ramda.type(fn3)
      Ramda.type(1)
      Ramda.type({ a : 1 })
      Ramda.type(null)
      Ramda.type(undefined)
      Ramda.type(Number('foo'))
      Ramda.type([ 12, 3 ])
      Ramda.type(/\s/g)
    },
  },
]

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

union

union<T>(x: readonly T[], y: readonly T[]): readonly T[]

It takes two lists and return a new list containing a merger of both list with removed duplicates.

R.equals is used to compare for duplication.

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

Try this R.union example in Rambda REPL

All Typescript definitions
union<T>(x: readonly T[], y: readonly T[]): readonly T[];
union<T>(x: readonly T[]): (y: readonly T[]) => readonly T[];
R.union source
import { includes } from './includes'

export function union(x, y){
  if (arguments.length === 1) return _y => union(x, _y)

  const toReturn = x.slice()

  y.forEach(yInstance => {
    if (!includes(yInstance, x)) toReturn.push(yInstance)
  })

  return toReturn
}
Tests
import { union } from './union'

test('happy', () => {
  expect(union([ 1, 2 ], [ 2, 3 ])).toEqual([ 1, 2, 3 ])
})

test('with list of objects', () => {
  const list1 = [ { a : 1 }, { a : 2 } ]
  const list2 = [ { a : 2 }, { a : 3 } ]
  const result = union(list1)(list2)
})
Typescript test
import {union} from 'rambda'

describe('R.union', () => {
  it('happy', () => {
    const result = union([1, 2], [2, 3])

    result // $ExpectType number[]
  })
  it('with array of objects - case 1', () => {
    const list1 = [{a: 1}, {a: 2}]
    const list2 = [{a: 2}, {a: 3}]
    const result = union(list1, list2)
    result // $ExpectType { a: number; }[]
  })
  it('with array of objects - case 2', () => {
    const list1 = [{a: 1, b: 1}, {a: 2}]
    const list2 = [{a: 2}, {a: 3, b: 3}]
    const result = union(list1, list2)
    result[0].a // $ExpectType number
    result[0].b // $ExpectType number | undefined
  })
})

describe('R.union - curried', () => {
  it('happy', () => {
    const result = union([1, 2])([2, 3])

    result // $ExpectType number[]
  })
  it('with array of objects - case 1', () => {
    const list1 = [{a: 1}, {a: 2}]
    const list2 = [{a: 2}, {a: 3}]
    const result = union(list1)(list2)
    result // $ExpectType { a: number; }[]
  })
  it('with array of objects - case 2', () => {
    const list1 = [{a: 1, b: 1}, {a: 2}]
    const list2 = [{a: 2}, {a: 3, b: 3}]
    const result = union(list1)(list2)
    result[0].a // $ExpectType number
    result[0].b // $ExpectType number | undefined
  })
})

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

uniq

uniq<T>(list: readonly T[]): readonly T[]

It returns a new array containing only one copy of each element of list.

R.equals is used to determine equality.

const list = [1, 1, {a: 1}, {a: 2}, {a:1}]

R.uniq(list)
// => [1, {a: 1}, {a: 2}]

Try this R.uniq example in Rambda REPL

All Typescript definitions
uniq<T>(list: readonly T[]): readonly T[];
R.uniq source
import { includes } from './includes'

export function uniq(list){
  let index = -1
  const willReturn = []

  while (++index < list.length){
    const value = list[ index ]

    if (!includes(value, willReturn)){
      willReturn.push(value)
    }
  }

  return willReturn
}
Tests
import { uniq } from './uniq'

test('happy', () => {
  expect(uniq([ 1, 2, 3, 3, 3, 1, 2, 0 ])).toEqual([ 1, 2, 3, 0 ])
  expect(uniq([ 1, 1, 2, 1 ])).toEqual([ 1, 2 ])
  expect([ 1, '1' ]).toEqual([ 1, '1' ])
  expect(uniq([ [ 42 ], [ 42 ] ])).toEqual([ [ 42 ] ])
})
Typescript test
import {uniq} from 'rambda'

describe('R.uniq', () => {
  it('happy', () => {
    const result = uniq([1, 2, 3, 3, 3, 1, 2, 0])
    result // $ExpectType number[]
  })
})
Lodash is fastest. Rambda is 98.98% slower and Ramda is 96.58% slower
const R = require('../../dist/rambda.js')

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

const uniq = [
  {
    label : 'Rambda',
    fn    : () => {
      R.uniq(list)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.uniq(list)
    },
  },
  {
    label : 'Lodash',
    fn    : () => {
      _.uniq(list)
    },
  },
]

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

uniqWith

uniqWith<T, U>(predicate: (x: T, y: T) => boolean, list: readonly T[]): readonly T[]

It returns a new array containing only one copy of each element in list according to predicate function.

This predicate should return true, if two elements are equal.

const list = [
  {id: 0, title:'foo'},
  {id: 1, title:'bar'},
  {id: 2, title:'baz'},
  {id: 3, title:'foo'},
  {id: 4, title:'bar'},
]

const expected = [
  {id: 0, title:'foo'},
  {id: 1, title:'bar'},
  {id: 2, title:'baz'},
]

const predicate = (x,y) => x.title === y.title

const result = R.uniqWith(predicate, list)
// => `result` is equal to `expected`

Try this R.uniqWith example in Rambda REPL

All Typescript definitions
uniqWith<T, U>(predicate: (x: T, y: T) => boolean, list: readonly T[]): readonly T[];
uniqWith<T, U>(predicate: (x: T, y: T) => boolean): (list: readonly T[]) => readonly T[];
R.uniqWith source
import { any } from './any'

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

  let index = -1
  const len = list.length
  const willReturn = []

  while (++index < len){
    const value = list[ index ]
    const flag = any(willReturnInstance => predicate(value, willReturnInstance),
      willReturn)

    if (!flag){
      willReturn.push(value)
    }
  }

  return willReturn
}
Tests
import { uniqWith } from './uniqWith'

test('happy', () => {
  const input = [
    {
      id    : 0,
      title : 'foo',
    },
    {
      id    : 1,
      title : 'bar',
    },
    {
      id    : 2,
      title : 'baz',
    },
    {
      id    : 3,
      title : 'foo',
    },
    {
      id    : 4,
      title : 'bar',
    },
  ]

  const expectedResult = [
    {
      id    : 0,
      title : 'foo',
    },
    {
      id    : 1,
      title : 'bar',
    },
    {
      id    : 2,
      title : 'baz',
    },
  ]

  const fn = (x, y) => x.title === y.title

  const result = uniqWith(fn, input)
  const curriedResult = uniqWith(fn)(input)

  expect(result).toEqual(expectedResult)

  expect(curriedResult).toEqual(expectedResult)
})

test('uniqWith', () => {
  const input = [
    {
      id    : 0,
      title : 'foo',
    },
    {
      id    : 1,
      title : 'bar',
    },
    {
      id    : 2,
      title : 'baz',
    },
    {
      id    : 3,
      title : 'foo',
    },
    {
      id    : 4,
      title : 'bar',
    },
  ]

  const expectedResult = [
    {
      id    : 0,
      title : 'foo',
    },
    {
      id    : 1,
      title : 'bar',
    },
    {
      id    : 2,
      title : 'baz',
    },
  ]

  const fn = (x, y) => x.title === y.title

  const result = uniqWith(fn, input)
  //const result = uniqWith(Ramda.eqBy(Ramda.prop('title')), input)

  expect(result).toEqual(expectedResult)
})
Typescript test
import {uniqWith} from 'rambda'

describe('R.uniqWith', () => {
  it('happy', () => {
    const input = [
      {
        id: 0,
        title: 'foo',
      },
      {
        id: 1,
        title: 'bar',
      },
      {
        id: 2,
        title: 'baz',
      },
      {
        id: 3,
        title: 'foo',
      },
      {
        id: 4,
        title: 'bar',
      },
    ]

    const fn = (x: any, y: any) => x.title === y.title

    const result = uniqWith(fn, input)
    result // $ExpectType { id: number; title: string; }[]
  })
})

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

unless

unless<T, U>(predicate: (x: T) => boolean, whenFalseFn: (x: T) => U, obj: T): U

The method returns function that will be called with argument input.

If predicate(input) returns false, then the end result will be the outcome of whenFalse(input).

In the other case, the final output will be the input itself.

const fn = R.unless(
  x => x > 2,
  x => x + 10
)

const result = [
  fn(1),
  fn(5)
]
// => [11, 5]

Try this R.unless example in Rambda REPL

All Typescript definitions
unless<T, U>(predicate: (x: T) => boolean, whenFalseFn: (x: T) => U, obj: T): U;
unless<T, U>(predicate: (x: T) => boolean, whenFalseFn: (x: T) => U): (obj: T) => U;
R.unless source
export function unless(predicate, whenFalse){
  if (arguments.length === 1){
    return _whenFalse => unless(predicate, _whenFalse)
  }

  return input => {
    if (predicate(input)) return input

    return whenFalse(input)
  }
}
Tests
import { inc } from './inc'
import { isNil } from './isNil'
import { unless } from './unless'

const safeInc = unless(isNil, inc)

test('happy', () => {
  expect(safeInc(null)).toBeNull()
  expect(safeInc(1)).toBe(2)
})

test('curried', () => {
  const safeIncCurried = unless(isNil)(inc)
  expect(safeIncCurried(null)).toBeNull()
  expect(safeIncCurried(1)).toBe(2)
})
Typescript test
import {unless, isNil, inc} from 'rambda'

describe('R.unless', () => {
  it('happy', () => {
    const safeInc = unless<any, number>(isNil, inc)
    const result = [safeInc(null), safeInc(1)]
    result[0] // $ExpectType number
    result[1] // $ExpectType number
  })

  it('it needs explicitly declared types', () => {
    const safeInc = unless(x => x > 5, inc)
    const result = safeInc(1)
    result // $ExpectType number
  })
})

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

update

update<T>(index: number, newValue: T, list: readonly T[]): readonly T[]

It returns a copy of list with updated element at index with newValue.

const index = 2
const newValue = 88
const list = [1, 2, 3, 4, 5]

const result = R.update(index, newValue, list)
// => [1, 2, 88, 4, 5]

Try this R.update example in Rambda REPL

All Typescript definitions
update<T>(index: number, newValue: T, list: readonly T[]): readonly T[];
update<T>(index: number, newValue: T): (list: readonly T[]) => readonly T[];
R.update source
import { curry } from './curry'

function updateFn(
  index, newValue, list
){
  const arrClone = list.slice()

  return arrClone.fill(
    newValue, index, index + 1
  )
}

export const update = curry(updateFn)
Tests
import { update } from './update'

const list = [ 1, 2, 3 ]

test('happy', () => {
  const newValue = 8
  const index = 1
  const result = update(
    index, newValue, list
  )
  const curriedResult = update(index, newValue)(list)
  const tripleCurriedResult = update(index)(newValue)(list)

  const expected = [ 1, 8, 3 ]
  expect(result).toEqual(expected)
  expect(curriedResult).toEqual(expected)
  expect(tripleCurriedResult).toEqual(expected)
})

test('list has no such index', () => {
  const newValue = 8
  const index = 10
  const result = update(
    index, newValue, list
  )

  expect(result).toEqual(list)
})
Typescript test
import {update} from 'rambda'

describe('R.update', () => {
  it('happy', () => {
    const result = update(1, 0, [1, 2, 3])
    result // $ExpectType number[]
  })
})
Rambda is faster than Ramda with 38.88%
const R = require('../../dist/rambda.js')

const list = [ 0, 1, 2 ]
const index = 1
const replacer = 7

const update = [
  {
    label : 'Rambda',
    fn    : () => {
      R.update(
        replacer, index, list
      )
      R.update(replacer, index)(list)
      R.update(replacer)(index)(list)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.update(
        replacer, index, list
      )
      Ramda.update(replacer, index)(list)
      Ramda.update(replacer)(index)(list)
    },
  },
]

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

values

values<T extends object, K extends keyof T>(obj: T): readonly T[K][]

With correct input, this is nothing more than Object.values(obj). If obj is not an object, then it returns an empty array.

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

R.values(obj)
// => [1, 2]

Try this R.values example in Rambda REPL

All Typescript definitions
values<T extends object, K extends keyof T>(obj: T): readonly T[K][];
R.values source
import { type } from './type'

export function values(obj){
  if (type(obj) !== 'Object') return []

  return Object.values(obj)
}
Tests
import { values } from './values'

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

test('with bad input', () => {
  expect(values(null)).toEqual([])
  expect(values(undefined)).toEqual([])
  expect(values(55)).toEqual([])
  expect(values('foo')).toEqual([])
  expect(values(true)).toEqual([])
  expect(values(false)).toEqual([])
  expect(values(NaN)).toEqual([])
  expect(values(Infinity)).toEqual([])
  expect(values([])).toEqual([])
})
Typescript test
import {values} from 'rambda'

describe('R.values', () => {
  it('happy', () => {
    const result = values({
      a: 1,
      b: 2,
      c: 3,
    })
    result // $ExpectType number[]
  })
})

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

view

view<T, U>(lens: Lens): (target: T) => U

It returns the value of lens focus over target object.

const lens = R.lensProp('x')

R.view(lens, {x: 1, y: 2}) // => 1
R.view(lens, {x: 4, y: 2}) // => 4

Try this R.view example in Rambda REPL

All Typescript definitions
view<T, U>(lens: Lens): (target: T) => U;
view<T, U>(lens: Lens, target: T): U;
R.view source
const Const = x => ({
  x,
  map : fn => Const(x),
})

export function view(lens, target){
  if (arguments.length === 1) return _target => view(lens, _target)

  return lens(Const)(target).x
}
Tests
import { assoc } from './assoc'
import { lens } from './lens'
import { prop } from './prop'
import { view } from './view'

const testObject = { foo : 'Led Zeppelin' }
const assocLens = lens(prop('foo'), assoc('foo'))

test('happy', () => {
  expect(view(assocLens, testObject)).toEqual('Led Zeppelin')
})
Typescript test
import {lens, view, assoc} from 'rambda'

interface Input {
  foo: string,
}

const testObject: Input = {
  foo: 'Led Zeppelin',
}

const fooLens = lens<Input, string, string>((x: Input) => {
  return x.foo
}, assoc('foo'))

describe('R.view', () => {
  it('happt', () => {
    const result = view<Input, string>(fooLens, testObject)
    result // $ExpectType string
  })
})
Rambda is faster than Ramda with 82.21%
const R = require('../../dist/rambda.js')

const testObj = { a : 1 }

const last = [
  {
    label : 'Rambda',
    fn    : () => {
      R.view(R.lensProp('a'), testObj)
    },
  },
  {
    label : 'Ramda',
    fn    : () => {
      Ramda.view(Ramda.lensProp('a'), testObj)
    },
  },
]

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

when

when<T, U>(predicate: (x: T) => boolean, whenTrueFn: (a: T) => U, input: T): T | U
All Typescript definitions
when<T, U>(predicate: (x: T) => boolean, whenTrueFn: (a: T) => U, input: T): T | U;
when<T, U>(predicate: (x: T) => boolean, whenTrueFn: (a: T) => U): (input: T) => T | U;
when<T, U>(predicate: (x: T) => boolean): ((whenTrueFn: (a: T) => U) => (input: T) => T | U);
R.when source
import { curry } from './curry'

function whenFn(
  predicate, whenTrueFn, input
){
  if (!predicate(input)) return input

  return whenTrueFn(input)
}

export const when = curry(whenFn)
Tests
import { add } from './add'
import { when } from './when'

const predicate = x => typeof x === 'number'

test('happy', () => {
  const fn = when(predicate, add(11))
  expect(fn(11)).toBe(22)
  expect(fn('foo')).toBe('foo')
})
Typescript test
import {when} from 'rambda'

const predicate = (x: number) => x > 2
const whenTrueFn = (x: number) => String(x)

describe('R.when', () => {
  it('happy', () => {
    const result = when(predicate, whenTrueFn, 1)
    result // $ExpectType string | 1
  })

  it('curry 1', () => {
    const fn = when(predicate, whenTrueFn)
    const result = fn(1)
    result // $ExpectType string | number
  })

  it('curry 2 require explicit types', () => {
    const fn = when<number, string>(predicate)(whenTrueFn)
    const result = fn(1)
    result // $ExpectType string | number
  })
})

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

where

where<T, U>(conditions: T, input: U): boolean

It returns true if all each property in conditions returns true when applied to corresponding property in input object.

R.equals is used to determine equality.

const condition = R.where({
  a : x => typeof x === "string",
  b : x => x === 4
})
const input = {
  a : "foo",
  b : 4,
  c : 11,
}

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

Try this R.where example in Rambda REPL

All Typescript definitions
where<T, U>(conditions: T, input: U): boolean;
where<T>(conditions: T): <U>(input: U) => boolean;
where<ObjFunc2, U>(conditions: ObjFunc2, input: U): boolean;
where<ObjFunc2>(conditions: ObjFunc2): <U>(input: U) => boolean;
R.where source
export function where(conditions, input){
  if (input === undefined){
    return _input => where(conditions, _input)
  }
  let flag = true
  for (const prop in conditions){
    const result = conditions[ prop ](input[ prop ])
    if (flag && result === false){
      flag = false
    }
  }

  return flag
}
Tests
import { equals } from './equals'
import { where } from './where'

test('when true', () => {
  const predicate = where({
    a : equals('foo'),
    b : equals('bar'),
  })
  expect(predicate({
    a : 'foo',
    b : 'bar',
    x : 11,
    y : 19,
  })).toEqual(true)
})

test('when false', () => {
  const predicate = where({
    a : equals('foo'),
    b : equals('baz'),
  })
  expect(predicate({
    a : 'foo',
    b : 'bar',
    x : 11,
    y : 19,
  })).toEqual(false)
})
Typescript test
import {where, equals} from 'rambda'

describe('R.where', () => {
  it('happy', () => {
    const input = {
      a: 'foo',
      b: 'bar',
      x: 11,
      y: 19,
    }
    const conditions = {
      a: equals('foo'),
      b: equals('bar'),
    }
    const result = where(conditions, input)
    const curriedResult = where(conditions)(input)
    result // $ExpectType boolean
    curriedResult // $ExpectType boolean
  })
})

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

whereEq

whereEq<T, U>(condition: T, input: U): boolean

It will return true if all of input object fully or partially include rule object.

R.equals is used to determine equality.

const condition = { a : { b : 1 } }
const input = {
  a : { b : 1 },
  c : 2
}

const result = whereEq(condition, input)
// => true

Try this R.whereEq example in Rambda REPL

All Typescript definitions
whereEq<T, U>(condition: T, input: U): boolean;
whereEq<T>(condition: T): <U>(input: U) => boolean;
R.whereEq source
import { equals } from './equals'
import { filter } from './filter'

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

  const result = filter((conditionValue, conditionProp) =>
    equals(conditionValue, input[ conditionProp ]),
  condition)

  return Object.keys(result).length === Object.keys(condition).length
}
Tests
import { whereEq } from './whereEq'

test('when true', () => {
  const condition = { a : 1 }
  const input = {
    a : 1,
    b : 2,
  }

  const result = whereEq(condition, input)
  const expectedResult = true

  expect(result).toEqual(expectedResult)
})

test('when false', () => {
  const condition = { a : 1 }
  const input = { b : 2 }

  const result = whereEq(condition, input)
  const expectedResult = false

  expect(result).toEqual(expectedResult)
})

test('with nested object', () => {
  const condition = { a : { b : 1 } }
  const input = {
    a : { b : 1 },
    c : 2,
  }

  const result = whereEq(condition)(input)
  const expectedResult = true

  expect(result).toEqual(expectedResult)
})

test('with wrong input', () => {
  const condition = { a : { b : 1 } }

  expect(() => whereEq(condition, null)).toThrowWithMessage(TypeError,
    'Cannot read property \'a\' of null')
})
Typescript test
import {whereEq} from 'rambda'

describe('R.whereEq', () => {
  it('happy', () => {
    const result = whereEq({a: {b: 2}}, {b: 2})
    const curriedResult = whereEq({a: {b: 2}})({b: 2})
    result // $ExpectType boolean
    curriedResult // $ExpectType boolean
  })
})

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

without

without<T>(matchAgainst: readonly T[], source: readonly T[]): readonly T[]

It will return a new array, based on all members of source list that are not part of matchAgainst list.

R.equals is used to determine equality.

const source = [1, 2, 3, 4]
const matchAgainst = [2, 3]

const result = R.without(matchAgainst, source)
// => [1, 4]

Try this R.without example in Rambda REPL

All Typescript definitions
without<T>(matchAgainst: readonly T[], source: readonly T[]): readonly T[];
without<T>(matchAgainst: readonly T[]): (source: readonly T[]) => readonly T[];
R.without source
import { includesArray } from './includes'
import { reduce } from './reduce'

export function without(matchAgainst, source){
  if (source === undefined){
    return _source => without(matchAgainst, _source)
  }

  return reduce(
    (prev, current) =>
    includesArray(current, matchAgainst) ? prev : prev.concat(current),
    [],
    source
  )
}
Tests
import { without } from './without'

test('should return a new list without values in the first argument ', () => {
  const itemsToOmit = [ 'A', 'B', 'C' ]
  const collection = [ 'A', 'B', 'C', 'D', 'E', 'F' ]

  expect(without(itemsToOmit, collection)).toEqual([ 'D', 'E', 'F' ])
  expect(without(itemsToOmit)(collection)).toEqual([ 'D', 'E', 'F' ])
})

test('ramda bug', () => {
  expect(
    without("0:1", ["0", "0:1"])
  ).toEqual(['0:1'])
})

test('ramda test', () => {
  expect(without([ 1, 2 ])([ 1, 2, 1, 3, 4 ])).toEqual([ 3, 4 ])
})
Typescript test
import {without} from 'rambda'

const itemsToOmit = ['A', 'B', 'C']
const collection = ['A', 'B', 'C', 'D', 'E', 'F']

describe('R.without', () => {
  it('happy', () => {
    const result = without(itemsToOmit, collection)

    result // $ExpectType string[]
  })
  it('curried', () => {
    const result = without(itemsToOmit)(collection)

    result // $ExpectType string[]
  })
})

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

xor

xor(x: boolean, y: boolean): boolean

Logical XOR

const result = [
  xor(true, true),
  xor(false, false),
  xor(false, true),
]
// => [false, false, true]

Try this R.xor example in Rambda REPL

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

  return Boolean(a) && !b || Boolean(b) && !a
}
Tests
import { xor } from './xor'

test('compares two values with exclusive or', () => {
  expect(xor(true, true)).toEqual(false)
  expect(xor(true, false)).toEqual(true)
  expect(xor(false, true)).toEqual(true)
  expect(xor(false, false)).toEqual(false)
})

test('when both values are truthy, it should return false', () => {
  expect(xor(true, 'foo')).toEqual(false)
  expect(xor(42, true)).toEqual(false)
  expect(xor('foo', 42)).toEqual(false)
  expect(xor({}, true)).toEqual(false)
  expect(xor(true, [])).toEqual(false)
  expect(xor([], {})).toEqual(false)
  expect(xor(new Date(), true)).toEqual(false)
  expect(xor(true, Infinity)).toEqual(false)
  expect(xor(Infinity, new Date())).toEqual(false)
})

test('when both values are falsy, it should return false', () => {
  expect(xor(null, false)).toEqual(false)
  expect(xor(false, undefined)).toEqual(false)
  expect(xor(undefined, null)).toEqual(false)
  expect(xor(0, false)).toEqual(false)
  expect(xor(false, NaN)).toEqual(false)
  expect(xor(NaN, 0)).toEqual(false)
  expect(xor('', false)).toEqual(false)
})

test('when one argument is truthy and the other is falsy, it should return true', () => {
  expect(xor('foo', null)).toEqual(true)
  expect(xor(null, 'foo')).toEqual(true)
  expect(xor(undefined, 42)).toEqual(true)
  expect(xor(42, undefined)).toEqual(true)
  expect(xor(Infinity, NaN)).toEqual(true)
  expect(xor(NaN, Infinity)).toEqual(true)
  expect(xor({}, '')).toEqual(true)
  expect(xor('', {})).toEqual(true)
  expect(xor(new Date(), 0)).toEqual(true)
  expect(xor(0, new Date())).toEqual(true)
  expect(xor([], null)).toEqual(true)
  expect(xor(undefined, [])).toEqual(true)
})
Typescript test
import {xor} from 'rambda'

describe('R.xor', () => {
  it('happy', () => {
    xor(true, false) // $ExpectType boolean
  })
  it('curry', () => {
    xor(true)(false) // $ExpectType boolean
  })
})

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

zip

zip<K, V>(x: readonly K[], y: readonly V[]): readonly KeyValuePair<K, V>[]

It will return a new array containing tuples of equally positions items from both x and y lists.

The returned list will be truncated to match the length of the shortest supplied list.

const x = [1, 2]
const y = ['A', 'B']
R.zip(x, y)
// => [[1, 'A'], [2, 'B']]

// truncates to shortest list
R.zip([...x, 3], ['A', 'B'])
// => [[1, 'A'], [2, 'B']]

Try this R.zip example in Rambda REPL

All Typescript definitions
zip<K, V>(x: readonly K[], y: readonly V[]): readonly KeyValuePair<K, V>[];
zip<K>(x: readonly K[]): <V>(y: readonly V[]) => readonly KeyValuePair<K, V>[];
R.zip source
export function zip(left, right){
  if (arguments.length === 1) return _right => zip(left, _right)

  const result = []
  const length = Math.min(left.length, right.length)

  for (let i = 0; i < length; i++){
    result[ i ] = [ left[ i ], right[ i ] ]
  }

  return result
}
Tests
import { zip } from './zip'

const array1 = [ 1, 2, 3 ]
const array2 = [ 'A', 'B', 'C' ]

test('should return an array', () => {
  const actual = zip(array1)(array2)
  expect(actual).toBeInstanceOf(Array)
})

test('should return and array or tuples', () => {
  const expected = [
    [ 1, 'A' ],
    [ 2, 'B' ],
    [ 3, 'C' ],
  ]
  const actual = zip(array1, array2)
  expect(actual).toEqual(expected)
})

test('should truncate result to length of shorted input list', () => {
  const expectedA = [
    [ 1, 'A' ],
    [ 2, 'B' ],
  ]
  const actualA = zip([ 1, 2 ], array2)
  expect(actualA).toEqual(expectedA)

  const expectedB = [
    [ 1, 'A' ],
    [ 2, 'B' ],
  ]
  const actualB = zip(array1, [ 'A', 'B' ])
  expect(actualB).toEqual(expectedB)
})
Typescript test
import {zip} from 'rambda'

describe('R.zip', () => {
  it('happy', () => {
    const array1 = [1, 2, 3]
    const array2 = ['A', 'B', 'C']

    const result = zip(array1)(array2)
    result // $ExpectType KeyValuePair<number, string>[]
  })
})

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

zipObj

zipObj<T, K extends string>(keys: readonly K[], values: readonly T[]): { readonly [P in K]: T }

It will return a new object with keys of keys array and values of values array.

const keys = ['a', 'b', 'c']

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

// truncates to shortest list
R.zipObj(keys, [1, 2])
// => {a: 1, b: 2}

Try this R.zipObj example in Rambda REPL

All Typescript definitions
zipObj<T, K extends string>(keys: readonly K[], values: readonly T[]): { readonly [P in K]: T };
zipObj<K extends string>(keys: readonly K[]): <T>(values: readonly T[]) => { readonly [P in K]: T };
zipObj<T, K extends number>(keys: readonly K[], values: readonly T[]): { readonly [P in K]: T };
zipObj<K extends number>(keys: readonly K[]): <T>(values: readonly T[]) => { readonly [P in K]: T };
R.zipObj source
import { take } from './take'

export function zipObj(keys, values){
  if (arguments.length === 1) return yHolder => zipObj(keys, yHolder)

  return take(values.length, keys).reduce((
    prev, xInstance, i
  ) => {
    prev[ xInstance ] = values[ i ]

    return prev
  }, {})
}
Tests
import { equals } from './equals'
import { zipObj } from './zipObj'

test('zipObj', () => {
  expect(zipObj([ 'a', 'b', 'c' ], [ 1, 2, 3 ])).toEqual({
    a : 1,
    b : 2,
    c : 3,
  })
})

test('0', () => {
  expect(zipObj([ 'a', 'b' ])([ 1, 2, 3 ])).toEqual({
    a : 1,
    b : 2,
  })
})

test('1', () => {
  expect(zipObj([ 'a', 'b', 'c' ])([ 1, 2 ])).toEqual({
    a : 1,
    b : 2,
  })
})

test('ignore extra keys', () => {
  const result = zipObj([ 'a', 'b', 'c', 'd', 'e', 'f' ], [ 1, 2, 3 ])
  const expected = {
    a : 1,
    b : 2,
    c : 3,
  }

  expect(equals(result, expected)).toBeTrue()
})
Typescript test
import {zipObj} from 'rambda'

describe('R.zipObj', () => {
  it('happy', () => {
    // this is wrong since 24.10.2020 `@types/ramda` changes
    const result = zipObj(['a', 'b', 'c', 'd'], [1, 2, 3])
    result // $ExpectType { b: number; a: number; c: number; d: number; }
  })
  it('imported from @types/ramda', () => {
    const result = zipObj(['a', 'b', 'c'], [1, 2, 3])
    const curriedResult = zipObj(['a', 'b', 'c'])([1, 2, 3])
    result // $ExpectType { b: number; a: number; c: number; }
    curriedResult // $ExpectType { b: number; a: number; c: number; }
  })
})

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

zipWith

zipWith<T, U, TResult>(fn: (x: T, y: U) => TResult, list1: readonly T[], list2: readonly U[]): readonly TResult[]
const list1 = [ 10, 20, 30, 40 ]
const list2 = [ 100, 200 ]

const result = R.zipWith(
  R.add, list1, list2
)
// => [110, 220]

Try this R.zipWith example in Rambda REPL

All Typescript definitions
zipWith<T, U, TResult>(fn: (x: T, y: U) => TResult, list1: readonly T[], list2: readonly U[]): readonly TResult[];
zipWith<T, U, TResult>(fn: (x: T, y: U) => TResult, list1: readonly T[]): (list2: readonly U[]) => readonly TResult[];
zipWith<T, U, TResult>(fn: (x: T, y: U) => TResult): (list1: readonly T[], list2: readonly U[]) => readonly TResult[];
R.zipWith source
import { curry } from './curry'
import { take } from './take'

function zipWithFn(
  fn, x, y
){
  return take(x.length > y.length ? y.length : x.length,
    x).map((xInstance, i) => fn(xInstance, y[ i ]))
}

export const zipWith = curry(zipWithFn)
Tests
import { add } from './add'
import { zipWith } from './zipWith'

const list1 = [ 1, 2, 3 ]
const list2 = [ 10, 20, 30, 40 ]
const list3 = [ 100, 200 ]

test('when second list is shorter', () => {
  const result = zipWith(
    add, list1, list3
  )
  expect(result).toEqual([ 101, 202 ])
})

test('when second list is longer', () => {
  const result = zipWith(
    add, list1, list2
  )
  expect(result).toEqual([ 11, 22, 33 ])
})
Typescript test
import {zipWith} from 'rambda'

const list1 = [1, 2]
const list2 = [10, 20, 30]

describe('R.zipWith', () => {
  it('happy', () => {
    const result = zipWith(
      (x, y) => {
        x // $ExpectType number
        y // $ExpectType number
        return `${x}-${y}`
      },
      list1,
      list2
    )

    result // $ExpectType string[]
  })
  it('curried', () => {
    const result = zipWith((x, y) => {
      x // $ExpectType unknown
      y // $ExpectType unknown
      return `${x}-${y}`
    })(list1, list2)

    result // $ExpectType string[]
  })
})

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

❯ CHANGELOG

WIP 6.7.0

  • Remove ts-toolbelt types from Typescript definitions. Most affected are the following methods, which lose one of its curried definitions:
  1. R.maxBy
  2. R.minBy
  3. R.pathEq
  4. R.viewOr
  5. R.when
  6. R.merge
  7. R.mergeDeepRight
  8. R.mergeLeft

6.6.0

  • Change R.piped typings to mimic that of R.pipe. Main difference is that R.pipe is focused on unary functions.

  • Fix wrong logic when R.without use R.includes while it should use array version of R.includes.

  • Use uglify plugin for UMD bundle.

  • Remove dist folder from .gitignore in order to fix Deno broken package. Issue #570

  • Improve R.fromPairs typings - Issue #567

6.5.3

  • Wrong logic where R.without use R.includes while it should use the array version of R.includes

This is Ramda bug, that Rambda also has before this release - https://github.com/ramda/ramda/issues/3086

6.5.2

  • Wrong R.defaultTo typings - changes introduced in v6.5.0 are missing their TS equivalent.

  • Update dependencies

6.5.1

Fix wrong versions in changelog

6.5.0

  • R.defaultTo no longer accepts infinite inputs, thus it follows Ramda implementation.

  • R.equals supports equality of functions.

  • R.pipe doesn't use R.compose.

  • Close Issue #561 - export several internal TS interfaces and types

  • Close Issue #559 - improve R.propOr typings

  • Add CHANGELOG.md file in release files list

6.4.0

  • Close Issue #560 - apply immutable lint to Typescript definitions

  • Close Issue #553 - fix problem with curried typings of R.prop

  • Fix wrong R.last typing

  • Upgrade all rollup related dependencies

  • R.type supports Symbol just like Ramda.

  • Remove file extension in main property in package.json in order to allow experimental-modules. See also this Ramda's PR - https://github.com/ramda/ramda/pull/2678/files

  • Import R.indexBy/R.when/R.zipObj/R.propEq/R.complement changes from recent @types/ramda release.

  • R.tryCatch stop supporting asynchronous functions; the previous behaviour is exported to Rambdax as R.tryCatchAsync

6.3.1

  • Fix missing Evolved declaration in Typescript definition

6.3.0

  • Add R.takeLastWhile

  • Add R.dropWhile

  • Add R.eqProps

  • Add R.dropLastWhile

  • Add R.dropRepeats

  • Add R.dropRepeatsWith

  • Add R.evolve

  • Add typings for R.takeWhile when iterable is a string

6.2.0

  • Add R.props

  • Add R.zipWith

  • Add R.splitAt

  • Add R.splitWhen

  • Close Issue #547 - restore readonly declaration in Typescript definitions.

  • R.append/R.prepend now work only with arrays just like Ramda. Previous behaviour was for them to work with both arrays and strings.

  • Sync R.pluck typings with @types/ramda as there was a tiny difference.

6.1.0

  • Fix R.and wrong definition, because the function doesn't convert the result to boolean. This introduce another difference with @types/ramda.

  • Add R.once

  • Add R.or

6.0.1

  • Fix typing of R.reject as it wrongly declares that with object, it pass property to predicate.

6.0.0

  • Breaking change - R.map/R.filter/R.reject/R.forEach/R.partition doesn't pass index as second argument to the predicate, when looping over arrays. The old behaviour of map, filter and forEach can be found in Rambdax methods R.mapIndexed, R.filterIndexed and R.forEachIndexed.

  • Breaking change - R.all/R.none/R.any/R.find/R.findLast/R.findIndex/R.findLastIndex doesn't pass index as second argument to the predicate.

  • Change R.assocPath typings so the user can explicitly sets type of the new object

  • Typings of R.assoc match its @types/ramda counterpart.

  • Simplify R.forEach typings

  • Remove ReadonlyArray<T> pattern from Typescript definitions - not enough value for the noise it adds.

5.13.1

  • Fix wrong R.takeWhile

5.13.0

  • Add R.takeWhile method

  • Fix R.lensPath issue when using string as path input. The issue was introduced when fixing Issue #524 in the previous release.

5.12.1

  • Close Issue #524 - wrong R.assocPath when path includes numbers

  • R.includes throws on wrong input, i.e. R.includes(1, null)

5.12.0

  • Add R.move method

  • Add R.union method

  • Close Issue #519 - ts-toolbelt needs other type of export with --isolatedModules flag

  • Change R.when implementation and typings to match those of Ramda

  • R.over and R.set use R.curry instead of manual currying

  • R.lensPath typings support string as path, i.e. 'a.b' instead of ['a', 'b']

  • R.equals now supports negative zero just like Ramda.equals

  • R.replace uses R.curry

5.11.0

Forgot to export R.of because of wrong marker in files/index.d.ts

5.10.0

Close Issue #514 - wrong R.length with empty string

Close Issue #511 - error in ts-toolbelt library

Close Issue #510 - R.clamp should throw if min argument is greater than max argument

  • PR #508 - add R.of

  • Definition of R.curry are not same as those of @types/ramda

  • Definitions of R.either is same as that of R.both

  • Definitions of R.ifElse no longer use any type

  • Definition of R.flatten requires passing type for the output

  • Fix definition of R.propOr, R.dissoc

  • Fix curried definitions of R.take, R.takeLast, R.drop and R.dropLast

  • 5.9.0

  • R.pickAll definition allows passing string as path to search.

  • R.propEq definition is now similar to that in @types/ramda.

  • R.none matches R.all implementation and pass index as second argument to predicate input.

  • R.reduce - drop support for object as iterable. Now it throws the same error as Ramda. Also instead of returning the initial value when iterable is undefined, now it throws.

Add index as additional argument to the Typescript definitions of the following methods:

  • R.all

  • R.find

  • R.findLast

  • R.findIndex

  • R.findLastIndex

  • 5.8.0

Add R.mergeAll Add R.mergeDeepRight Add R.mergeLeft Add R.partition Add R.pathEq Add R.tryCatch Add R.unless Add R.whereEq Add R.where

  • Add R.last typing for empty array

  • 5.7.0 Revert PR #469 as R.curry was slow | Also now R.flip throws if arity is greater than or equal to 5

  • 5.6.3 Merge several PRs of @farwayer

  • PR #482 - improve R.forEach performance by not using R.map

  • PR #485 - improve R.map performance

  • PR #482 - improve R.reduce performance

  • Fix missing high arity typings for R.compose/pipe

  • R.merge definitions match those of @types/ramda

  • Remove dist folder from Rambda repo

  • 5.6.2

Close Issue #476 - typesafe R.propEq definitions

Approve PR #477 - fix R.groupWith when list length is 1

  • 5.6.1

Update ts-toolbelt files as now there is update pipeline for it.

Approve PR #474 - intruduce internal isArray helper

  • 5.6.0

Approve PR #469 - R.flip supports any arity | implement R.curry with R.curryN add R.applySpec

  • 5.5.0

Close Issue #464 - R.flip should handle functions with arity above 2

Close Issue #468 - fs-extra should be dev dependency as it was wrongly added as production dependency in 5.2.0

R.flip typings now match @types/ramda typings

Add R.hasPath method

Add R.mathMod typings

  • 5.4.3

Fix R.omit typings

  • 5.4.2

Fix R.pick typings

Close Issue #460 - R.paths should be curried

  • 5.4.1

Close Issue #458 - wrong R.propIs typing

  • 5.4.0

Close Issue #408 - add R.chain

  • 5.3.0

Close Issue #430 - add R.when

Also restore R.converge, R.findLast, R.findLastIndex and R.curryN as I have forgotten to export them when releasing 5.2.0.

  • 5.2.1

Fix Typescript comment for every method

  • 5.2.0

Release new documentation site

Ramda repo now holds all Rambdax methods and tests

  • 5.1.1

Add R.converge and R.curryN from PR #412

Close Issue #410 - wrong implementation of R.groupWith

Close Issue #411 - change the order of declared R.map typings rules

  • 5.0.0

Move R.partialCurry to Rambdax(reason for major bump).

Use new type of export in Typescript definitions.

Approve PR #381 - add R.applySpec

  • 4.6.0

Approve PR #375 - add lenses(Thank you @synthet1c)

Add R.lens

Add R.lensIndex

Add R.lensPath

Add R.lensProp

Add R.over

Add R.set

Add R.view

Sync with Ramda 0.27

Add R.paths

Add R.xor

Close Issue #373

Add R.cond

  • 4.5.0 Add R.clamp

  • 4.4.2 Improve R.propOr typings

  • 4.4.1 Make R.reject has the same typing as R.filter

  • 4.4.0 Several changes:

Close Issue #317 - add R.transpose

Close Issue #325 - R.filter should return equal values for bad inputs null and undefined

Approve suggestion for R.indexBy to accept string not only function as first argument.

Edit of R.path typings

  • 4.2.0 Approve PR #314 - add R.and

  • 4.1.1 Add missing typings for R.slice

  • 4.1.0 Add R.findLast and R.findLastIndex

  • 4.0.2 Fix R.isEmpty wrong behaviour compared to the Ramda method

  • 4.0.1 Approve PR #289 - remove console.log in R.values method

  • 4.0.0 Multiple breaking changes as Rambda methods are changed in order to increase the similarity between with Ramda

Add to Differences:

R.type can return 'NaN'

R.compose doesn't pass `this` context

R.clone doesn't work with number, booleans and strings as input

All breaking changes:

-- R.add works only with numbers

-- Fix R.adjust which had wrong order of arguments

-- R.adjust works when index is out of bounds

-- R.complement support function with multiple arguments

-- R.compose/pipe throws when called with no argument

-- R.clone works with Date value as input

-- R.drop/dropLast/take/takeLast always return new copy of the list/string

-- R.take/takeLast return original list/string with negative index

-- R.equals handles NaN and RegExp types

-- R.type/R.equals supports new Boolean/new Number/new Date/new String expressions

-- R.has works with non-object

-- R.ifElse pass all arguments

-- R.length works with bad input

-- R.propEq work with bad input for object argument

-- R.range work with bad inputs

-- R.times work with bad inputs

-- R.reverse works with strings

-- R.splitEvery throws on non-positive integer index

-- R.test throws just like Ramda when first argument is not regex

-- R.values works with bad inputs

-- R.zipObj ignores extra keys

  • 3.3.0

This is pre 4.0.0 release and it contains all of the above changes

Close issue #287 - ts-toolbelt directory was changed but not reflected in files property in package.json

  • 3.2.5

Close issue #273 - ts-toolbelt needs other type of export when isolatedModules TypeScript property

Close issue #245 - complete typings tests for methods that have more specific Typescript definitions

  • 3.2.1 Fast fix for issue #273 - messed up typings

  • 3.2.0 There are several changes:

Close issue #263 - broken curry typing solved by ts-toolbelt local dependency.

Add R.partialCurry typings.

Approve PR #266 that adds R.slice method.

  • 3.1.0 This might be breaking change for Typescript users, as very different definitions are introduced. With the previous state of the definitions, it was not possible to pass dtslint typings tests.

  • R.either and R.both supports multiple arguments as they should.

  • Several methods added by @squidfunk - R.assocPath, R.symmetricDifference, R.intersperse, R.intersection and R.difference

  • 3.0.1 Close issue #234 - wrong curry typing

  • 3.0.0 Deprecate R.contains, while R.includes is now following Ramda API(it uses R.equals for comparision)

  • 2.14.5 R.without needs currying

  • 2.14.4 Close issue #227 - add index as third argument of R.reduce typings

  • 2.14.2 Use R.curry with R.reduce as manual curry there didn't work as expected.

  • 2.14.1 Fix wrong typescript with R.head - PR #228 pushed by @tonivj5

  • 2.14.0 Add R.groupWith by @selfrefactor | Add R.propOr, R.mathMod, R.mean, R.median, R.negate, R.product by @ku8ar

  • 2.13.0 Add R.identical - PR #217 pushed by @ku8ar

  • 2.12.0 Add R.propIs - PR #213 and add R.sum - issue #207

  • 2.11.2 Close Rambdax issue #32 - wrong R.type when function is input

  • 2.11.1 Approve PR #182 - Changed typings to allow object as input to R.forEach and R.map

  • 2.11.0 Approve PR #179 - R.adjust handles negative index; R.all doesn't need R.filter

  • 2.10.2 Close issue #175 - missing typescript file

  • 2.10.0 Approve huge and important PR #171 submitted by @helmuthdu - Add comments to each method, improve Typescript support

  • 2.9.0 R.toPairs and R.fromPairs

  • 2.8.0 Approve PR #165 R.clone

  • 2.7.1 expose src | Discussed at issue #147

  • 2.7.0 Approve PR #161 R.isEmpty

  • 2.6.0 R.map, R.filter and R.forEach pass original object to iterator as third argument | Discussed at issue #147

  • 2.5.0 Close issue #149 Add R.partial | R.type handles NaN

  • 2.4.0 Major bump of Rollup; Stop building for ES5

  • 2.3.1 Close issue #90 | Add string type of path in R.pathOr

  • 2.3.0 Close issue #89 | Fix missing Number TS definition in R.type

  • 2.2.0 R.defaultTo accepts indefinite number of input arguments. So the following is valid expression: const x = defaultTo('foo',null, null, 'bar')

  • 2.1.0 Restore R.zip using WatermelonDB implementation.

  • 2.0.0 Major version caused by removing of R.zip and R.addIndex. Issue #85 rightfully finds that the implementation of R.addIndex is not correct. This led to removing this method and also of R.zip as it had depended on it. The second change is that R.map, R.filter are passing array index as second argument when looping over arrays. The third change is that R.includes will return false if input is neigher string nor array. The previous behaviour was to throw an error. The last change is to increase the number of methods that are passing index as second argument to the predicate function.

  • 1.2.6 Use src folder instead of modules

  • 1.2.5 Fix omit typing

  • 1.2.4 Add missing Typescript definitions - PR#82

  • 1.2.2 Change curry method used across most of library methods

  • 1.2.1 Add R.assoc | fix passing undefined to R.map and R.merge issue #77

  • 1.2.0 Add R.min, R.minBy, R.max, R.maxBy, R.nth and R.keys

  • 1.1.5 Close issue #74 R.zipObj

  • 1.1.4 Close issue #71 CRA fail to build rambda

  • 1.1.3 Approve PR #70 implement R.groupBy | Close issue #69

  • 1.1.2 Approve PR #67 use babel-plugin-annotate-pure-calls

  • 1.1.1 Approve PR #66 R.zip

  • 1.1.0 R.compose accepts more than one input argument issue #65

  • 1.0.13 Approve PR #64 R.indexOf

  • 1.0.12 Close issue #61 make all functions modules

  • 1.0.11 Close issue #60 problem with babelrc

  • 1.0.10 Close issue #59 add R.dissoc

  • 1.0.9 Close issue #58 - Incorrect R.equals

  • 1.0.8 R.map and R.filter pass object properties when mapping over objects

  • 1.0.7 Add R.uniqWith

  • 1.0.6 Close issue #52 - ES5 compatible code

  • 1.0.5 Close issue #51

  • 1.0.4 Close issue #50 - add R.pipe typings

  • 1.0.3 R.ifElse accept also boolean as condition argument

  • 1.0.2 Remove typedDefaultTo and typedPathOr | Add R.pickAll and R.none

  • 1.0.0 Major change as build is now ES6 not ES5 compatible (Related to issue #46)| Making Rambda fully tree-shakeable| Edit Typescript definition

  • 0.9.8 Revert to ES5 compatible build - issue #46

  • 0.9.7 Refactor for Rollup tree-shake | Remove R.padEnd and R.padStart

  • 0.9.6 Close issue #44 - R.reverse mutates the array

  • 0.9.5 Close issue #45 - invalid Typescript typings

  • 0.9.4 Add R.reject and R.without (PR#41 PR#42) | Remove 'browser' field in package.json due to Webpack bug 4674

  • 0.9.3 Add R.forEach and R.times

  • 0.9.2 Add Typescript definitions

  • 0.9.1 Close issue #36 - move current behaviour of defaultTo to a new method typedDefaultTo; make defaultTo follow Ramda spec; add pathOr; add typedPathOr.

  • 0.9.0 Add R.pipe PR#35

  • 0.8.9 Add R.isNil

  • 0.8.8 Migrate to ES modules PR33 | Add R.flip to the API | R.map/filter works with objects

  • 0.8.7 Change Webpack with Rollup - PR29

  • 0.8.6 Add R.tap and R.identity

  • 0.8.5 Add R.all, R.allPass, R.both, R.either and R.complement

  • 0.8.4 Learning to run yarn test before yarn publish the hard way

  • 0.8.3 Add R.always, R.T and R.F

  • 0.8.2 Add concat, padStart, padEnd, lastIndexOf, toString, reverse, endsWith and startsWith methods

  • 0.8.1 Add R.ifElse

  • 0.8.0 Add R.not, R.includes | Take string as condition for R.pick and R.omit

  • 0.7.6 Fix incorrect implementation of R.values

  • 0.7.5 Fix incorrect implementation of R.omit

  • 0.7.4 issue #13 - Fix R.curry, which used to return incorrectly function when called with more arguments

  • 0.7.3 Close issue #9 - Compile to es2015; Approve PR #10 - add R.addIndex to the API

  • 0.7.2 Add Promise support for R.type

  • 0.7.1 Close issue #7 - add R.reduce to the API

  • 0.7.0 Close issue #5 - change name of curry to partialCurry; add new method curry, which works just like Ramda's curry

  • 0.6.2 Add separate documentation site via docsify

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

❯ Additional info

Most influential contributors

  • @farwayer - improving performance in R.find, R.filter; give the idea how to make benchmarks more reliable;

  • @thejohnfreeman - add R.assoc, R.chain;

  • @helmuthdu - add R.clone; help improve code style;

  • @jpgorman - add R.zip, R.reject, R.without, R.addIndex;

  • @ku8ar - add R.slice, R.propOr, R.identical, R.propIs and several math related methods; introduce the idea to display missing Ramda methods;

  • @romgrk - add R.groupBy, R.indexBy, R.findLast, R.findLastIndex;

  • @squidfunk - add R.assocPath, R.symmetricDifference, R.difference, R.intersperse;

  • @synthet1c - add all lenses methods; add R.applySpec, R.converge;

  • @vlad-zhukov - help with configuring Rollup, Babel; change export file to use ES module exports;

Rambda references

Links to Rambda

Deprecated from Used by section

Releases

Rambda's releases before 6.4.0 were used mostly for testing purposes.

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

My other libraries

Niketa theme

Collection of 9 light VSCode themes

Niketa dark theme

Collection of 9 dark VSCode themes

String-fn

String utility library

Useful Javascript libraries

Large collection of JavaScript,Typescript and Angular related repos links

Run-fn

CLI commands for lint JS/TS files, commit git changes and upgrade of dependencies
Comments
  • Dealing with readonly types returned from immutable array operations

    Dealing with readonly types returned from immutable array operations

    I'm having a problem using rambda for ngrx selectors that requires me to explicitly set readonly on immutable values to match the typescript definitions in rambda. It is also out of alignment with Ramda which does not force immutable return values through readonly.

    Would you consider removing the readonly return type to keep type definitions as concise and compatible as possible? or do you think it's important to force immutable Arrays and Objects?

    If I use Rambda.filter in my selector the return type is readonly Foo[]

    const selectRambdaFoos = createSelector(
      selectAllFoos,
      Rambda.filter<Foo>(identity), // becomes `readonly Foo[]`
    )
    // => Selector<object, readonly Foo[]>
    

    If I use Ramda.filter in my selector the return type is Foo[] (although I can't even get it to work, but the type signature should do this)

    const selectRamdaFoos = createSelector(
      selectAllFoos,
      Ramda.filter<Foo>(identity),
    )
    // => Selector<object, Foo[]>
    

    Where using imperative code wouldn't require the interface to be readonly

    const selectImperativeFoos = createSelector(
      selectAllFoos,
      foos => foos.filter(R.identity),
    )
    // => Selector<object, Foo[]>
    

    I can get around it by changing the type where I consume the selected observable, but is there any better way to deal with it? I would like to use rambda for my new job, but don't think it's a good idea at the start to change all their code to suit rambda, and I'm not sure what will happen if I then pipe that value into something else that I don't control that won't accept readonly interfaces.

    @Component({ ... })
    class FooComponent implements OnInit {
    
      $ramdaFoos: Observable<Foo[]>
    
      /* readonly property added to interface */
      $rambdaFoos: Observable<readonly Foo[]>
    
      constructor(private store: Store<AppState>){}
    
      ngOnInit(): void {
        this.rambdaFoos$ = this.store.pipe(select(selectRambdaFoos))
        this.ramdaFoos$ = this.store.pipe(select(selectRamdaFoos))
      }
    }
    

    Here is a working stackblitz if you need it. https://stackblitz.com/edit/rambda-readonly-issue?file=src/app/courses/reducers/courses.reducer.ts https://stackblitz.com/edit/rambda-readonly-issue?file=src/app/courses/components/course-list/course-list.component.ts

    Cheers

    opened by synthet1c 33
  • issue with typings

    issue with typings

    when trying and compiling my project I get errors on rambda typings?

    node_modules/rambda/index.d.ts:74:34 - error TS2503: Cannot find namespace 'F'.
    
    74     assocPath<T, U>(path: Path): F.Curry<(a: T, b: U) => U>;
                                        ~
    
    node_modules/rambda/index.d.ts:152:51 - error TS2503: Cannot find namespace 'Curry'.
    
    152     curry<F extends (...args: any) => any>(f: F): Curry.Curry<F>;
                                                          ~~~~~
    
    node_modules/rambda/index.d.ts:439:37 - error TS2503: Cannot find namespace 'Curry'.
    
    439     maxBy<T>(keyFn: (a: T) => Ord): Curry.Curry<(a: T, b: T) => T>;
                                            ~~~~~
    
    node_modules/rambda/index.d.ts:473:37 - error TS2503: Cannot find namespace 'Curry'.
    
    473     minBy<T>(keyFn: (a: T) => Ord): Curry.Curry<(a: T, b: T) => T>;
                                            ~~~~~
    
    node_modules/rambda/index.d.ts:544:29 - error TS2314: Generic type 'Exclude' requires 2 type argument(s).
    
    544     ) : (input: Pick<Input, Exclude<keyof PartialInput>>) => Output
                                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    node_modules/rambda/index.d.ts:558:33 - error TS2503: Cannot find namespace 'Curry'.
    
    558     pathOr<T>(defaultValue: T): Curry.Curry<(a: Path, b: any) => any>;
                                        ~~~~~
    
    node_modules/rambda/index.d.ts:818:52 - error TS2304: Cannot find name 'T'.
    
    818       <P extends string>(name: P): (obj: Record<P, T>) => boolean;
                                                           ~
    
    node_modules/rambda/index.d.ts:825:30 - error TS2304: Cannot find name 'Placeholder'.
    
    825     propOr<T, U>(val: T, __: Placeholder, obj: U): <V>(p: string) => V;
                                     ~~~~~~~~~~~
    
    node_modules/rambda/index.d.ts:826:19 - error TS2304: Cannot find name 'Placeholder'.
    
    826     propOr<U>(__: Placeholder, p: string, obj: U): <T, V>(val: T) => V;
                          ~~~~~~~~~~~
    
    node_modules/rambda/index.d.ts:844:65 - error TS2304: Cannot find name 'Reduced'.
    
    844     reduce<T, TResult>(fn: (acc: TResult, elem: T) => TResult | Reduced<TResult>, acc: TResult, list: ReadonlyArray<T>): TResult;
                                                                        ~~~~~~~
    
    node_modules/rambda/index.d.ts:845:65 - error TS2304: Cannot find name 'Reduced'.
    
    845     reduce<T, TResult>(fn: (acc: TResult, elem: T) => TResult | Reduced<TResult>): (acc: TResult, list: ReadonlyArray<T>) => TResult;
                                                                        ~~~~~~~
    
    node_modules/rambda/index.d.ts:846:65 - error TS2304: Cannot find name 'Reduced'.
    
    846     reduce<T, TResult>(fn: (acc: TResult, elem: T) => TResult | Reduced<TResult>, acc: TResult): (list: ReadonlyArray<T>) => TResult;
                                                                        ~~~~~~~
    
    node_modules/rambda/index.d.ts:852:13 - error TS2304: Cannot find name 'Filter'.
    
    852     reject: Filter;
    

    tsconfig

    {
      "compilerOptions": {
        /* Basic Options */
        "incremental": true,                      /* Enable incremental compilation */
        "target": "ES2019",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
        "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
        "lib": ["es2019"],                        /* Specify library files to be included in the compilation. */
        "outDir": "./build",                      /* Redirect output structure to the directory. */
        "rootDir": "./src",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
        "importHelpers": true,                    /* Import emit helpers from 'tslib'. */
    
        /* Strict Type-Checking Options */
        "strict": true,                           /* Enable all strict type-checking options. */
    
        /* Additional Checks */
    
        /* Module Resolution Options */
        "moduleResolution": "node",                /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
        "esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
      }
     
    }
    
    opened by shomodj 25
  • The `first` and `last` methods should have `undefined` in their return type signature

    The `first` and `last` methods should have `undefined` in their return type signature

    If the array is empty, first and last return undefined, but their type signatures say that they return an array item.

    (This could be considered a breaking change.)

    opened by rakeshpai 18
  • Pipe typings not seeming to work..

    Pipe typings not seeming to work..

    typescript: 3.9.3 rambda: 5.4.3

    R.pipe<number[]>( shuffle, R.take(5), R.append(10), shuffle, )([0,1,2,3,4,6]) }

    With the above code I get the following error: Expected 1 arguments, but got 4

    Please can someone point out to me what im doing wrong?

    opened by Revilotom 16
  • Many benchmarks are wrong and do not reflect reality

    Many benchmarks are wrong and do not reflect reality

    First of all thank you for the great library! I used it in many projects.

    But rambda is not so fast as you can think. Many popular functions are much slower than ramda and lodash. The reason of the misconception is in wrong benchmarks.

    Lets start from theory. Most functions for processing data consist of two stages: initialization and processing. In initialization part fn checks data type, arity, makes some preinitializaton etc. In main part fn processing data. Performance of both is important and they should be as fast as possible.

    If you pass a lot of data to function than processing stage becomes most important. But initialization stage is important too for use case when you are calling function very often. For example filtering small inner arrays of large list:

    map(filter(), [[1,2,3], [4,5,6], ... hundreds of thousands inner arrays ...])
    

    Filter will be called many time with small data set.

    So to test performance of both stages we need to have two tests: in first we pass a lot of data (testing processing stage) and in second we pass empty data set to execute all initialization checks but skip processing (testing init stage). Rambda in benchmarks uses only variant closest to init testing (several items passed only).

    And some another important things:

    1. All executing branches should be covered for worst cases (or at least for the most commonly used). For example condition for filter should always return true to fully test performance of adding items to new array/object.
    2. User code passed to function must be as fast as possible. To correctly testing speed of fn not user code. Ideally something that VM can optimize to const like noop function or function always returns true/false.

    Now I will show some proof of wrong benchmarks:

    1. find
    • empty array (init stage testing)
      Rambda:
        210 927 688 ops/s, ±0.77%   | fastest
      Ramda:
        3 244 120 ops/s, ±1.60%     | slowest, 98.46% slower
      Lodash:
        21 610 387 ops/s, ±1.27%    | 89.75% slower
    

    Yahoo! Fastest. Because no init (only arity check). Lets test with more data...

    • 10k items with const false predicate (processing stage testing)
      Rambda:
        12 524 ops/s, ±1.54%    | slowest, 93.88% slower
      Ramda:
        204 510 ops/s, ±1.18%   | fastest
      Lodash:
        144 455 ops/s, ±0.82%   | 29.37% slower
    

    But wait...

    2020-05-30-221358_521x55_scrot

    1. reduce
    • empty array
      Rambda:
        9 534 810 ops/s, ±2.80%     | 94.44% slower
      Ramda:
        5 777 626 ops/s, ±1.78%     | slowest, 96.63% slower
      Lodash:
        171 437 207 ops/s, ±0.96%   | fastest
    

    Ok, init much slower than for lodash and the same as ramda. What about processing performance?

    • 10k items with noop reducer
      Rambda:
        9 634 ops/s, ±3.09%     | slowest, 95.4% slower
      Ramda:
        209 617 ops/s, ±1.07%   | fastest
      Lodash:
        12 152 ops/s, ±1.12%    | 94.2% slower
    

    And then:

    2020-05-30-222623_529x52_scrot In reality ramda is fastest and ramda is 95% slower.

    I can help with making rambda fastest in the west (saw many places in code where optimization can be done). But we need to add several benchs for functions.

    As starting points: #472 #473 #474. No generated files, only source changes.

    opened by farwayer 15
  • Mutable API

    Mutable API

    Rambda's reverse modifies the array, instead of returning reversed copy of it.

    Just wanted to ask why? When you create a new reversed array it's probably just a shallow copy. There's no need to "fight" for RAM too much as JS already has memory sharing built-in. It's just not protected sharing and we protect it by convention with Ramda approach.

    let xs = [{...}, {...}, {...}]
    //
    let ys = [xs[2], xs[1], xs[0]]
    

    ys does not double the memory usage. It's only additional pointers (4 bytes each)!

    I.m.o the convention of "every function here is immutable" has to be kept at any cost.

    opened by ivan-kleshnin 15
  • defaultsTo shouldn't factor in type

    defaultsTo shouldn't factor in type

    As far as I can tell defaultsTo(defaultArgument, inputArgument) is the only method that provides a way for defaulting to a value (providing some 'or' logic). However, the built-in test for inputArgument being the same type as defaultArgument limits the use of this function. It is my opinion that defaultArgument should only be returned if inputArgument is undefined.

    I would like to compose a function works the same as Lodash's get method or Ramda's pathOr method whereby a value is read from a path through a nested object tree and defaults to a value if this path returns undefined.

    import { get } from 'lodash'
    import { pathOr } from 'ramda'
    import { curry, defaultsTo, path } from 'rambda'
    
    // Tests written with jest
    
    test('lodash get', () => {
      expect(get({ a: { b: 2 } }, 'a.b')).toBe(2)
      expect(get({ c: { b: 2 } }, 'a.b')).toBeUndefined()
      expect(get({ c: { b: 2 } }, 'a.b', 'N/A')).toBe('N/A')
    })
    
    test('ramda pathOr', () => {
      // From ramda's docs http://ramdajs.com/docs/#pathOr
      expect(pathOr('N/A', ['a', 'b'], { a: { b: 2 } })).toBe(2)
      expect(pathOr('N/A', ['a', 'b'], { c: { b: 2 } })).toBe('N/A')
    })
    
    // There's probably a more elegant way of doing this?
    const rambdaPathOr = curry((defaultValue, inputPath, inputValue) =>
      defaultTo(defaultValue, path(inputPath, inputValue)))
    
    test('rambda pathOr', () => {
      // This first test fails because the value of a.b is 2 (type 'Number')
      // and is a different type to the default value 'N/A' (type 'String')
      expect(rambdaPathOr('N/A', ['a', 'b'], { a: { b: 2 } })).toBe(2)
      expect(rambdaPathOr('N/A', ['a', 'b'], { c: { b: 2 } })).toBe('N/A')
    })
    
    opened by wagerfield 15
  • Webpack optimization bailout due to side effects in rambda.mjs

    Webpack optimization bailout due to side effects in rambda.mjs

    Hi and thanks for the lib!

    While replacing lodash with rambda I found that webpack optimizations cannot be performed due to top-level variables. Basically, webpack treats variable definitions, such as const adjust = curry(adjustFn) as a side-effect. The actual error/warning from webpack is

    Statement (VariableDeclaration) with side effects in source code at 28:0-31
    

    I've also made a reproduction repo - https://github.com/fatawesome/rambda-side-effects-example What do you think on this issue?

    done waiting release 
    opened by fatawesome 14
  • Curry trouble (example for R.is)

    Curry trouble (example for R.is)

    Hi,

    I understand this has to do with curry, but I constantly have trouble with R.is because of this, so... The troube comes when I do something like this if (R.is(Array, someVar)) { ... } Now, if someVar is undefined then R.is will return function, so the check will pass. This may happen in a bigger scope, when my function accepts an object A, and one of its fields B should be an array:

    function myFunc(A) {
    ...
      if (R.is(Array, A.B)) { ... }
    ...
    }
    

    So, if B was not defined, the IF block will proceed as if B were an array. I can add an additional check if (A.B && R.is(Array, A.B)) { ... } But that just doesn't feel and look right. Right?

    opened by noobiek 14
  • New library that doesn't follow Ramda API

    New library that doesn't follow Ramda API

    It is time to rebrand the library as it makes it very hard for branding and remembering while it is so close to Ramda. The new library will not aim to follow Ramda API so that can help in making hard decisions.

    Rambda will remain as it is, i.e. following Ramda API and receiving updates, but Rambdax will receive lower priority and stop receiving regular updates. Rambdax will only publish bugfixes and it will be synced with latest Rambda releases.

    Naming is still ongoing question.

    opened by selfrefactor 13
  • R.allPass doesn't accept more than 1 parameters for function predicates

    R.allPass doesn't accept more than 1 parameters for function predicates

    R.allPass is returning false for this case

    var plusEq = function(w, x, y, z) {return w + x === y + z; };
    
    console.log(R.allPass([plusEq])(3,3,3,3))
    

    output: false

    opened by mohit61 12
  • types of path are breaking in 7.4.0

    types of path are breaking in 7.4.0

    When updating to version 7.4.0 from 7.3.0, the usage of path is breaking. In our code we use the un-curried version:

    path<unknown>(['string','array'], object)
    

    I do not see types for an un-curried version using RamdaPath - is this intended?

    path<unknown>(['string','array'])(object)
    

    works out.

    I would have expected something like

    export function path<T>(pathToSearch: RamdaPath, obj: any) => T | undefined;
    

    to be part of the types.

    in progress 
    opened by Retro64 4
  • yarn out doesn't work

    yarn out doesn't work

    When I try to run yarn out it says

    yarn run v1.22.19
    $ yarn populatedocs && yarn populatereadme && yarn immutable && yarn build
    $ cd ../rambda-scripts && yarn populate:docs
    $ RAMBDA_SCRIPTS_MODE=populate:docs jest src/apply-rambda-scripts.spec.ts
    ● Validation Error:
    
      Preset ts-jest not found.
    
      Configuration Documentation:
      https://jestjs.io/docs/configuration
    
    error Command failed with exit code 1.
    info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
    error Command failed with exit code 1.
    info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
    error Command failed with exit code 1.
    info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
    

    It seems that running yarn add -D ts-jest in the scripts repo fixes it, for me.

    in progress 
    opened by agriffis 1
  • Regression in rambda 7.4

    Regression in rambda 7.4

    Wenn upgrading from earlier version to 7.4, the following error is thrown in a project using rambda:

    import { pathOr } from 'rambda';
             ^^^^^^
    SyntaxError: Named export 'pathOr' not found. The requested module 'rambda' is a CommonJS module, which may not support all module.exports as named exports.
    CommonJS modules can always be imported via the default export, for example using:
    
    import pkg from 'rambda';
    const { pathOr } = pkg;
    // [...]
    

    Nodejs version: v16.18.1. package.json includes "type": "module".

    in progress 
    opened by Phygon 3
  • feat: Improve `startsWith`, `includes` and `endsWith` typings for TS 4.5

    feat: Improve `startsWith`, `includes` and `endsWith` typings for TS 4.5

    There might be a better title for this PR.

    Starting from TypeScript 4.5 strings can be narrowed: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-5.html#template-string-types-as-discriminants

    Also see https://github.com/microsoft/TypeScript/pull/46137#issuecomment-932730666

    Should I do the same in @types/ramda as well?

    Also I noticed absence of formatter. Don't you mind enabling something like Prettier?

    opened by zardoy 6
Releases(v7.4.0)
Owner
Dejan Toteff
Unnecessary complexity killed the cat
Dejan Toteff
~900 byte minified CSV parser and builder. Smaller when compressed. Built in ESM only.

but-csv ~900 byte minified CSV parser and builder. Smaller when compressed. Built in ESM only. Doesn't care about headers, keyed rows, anything but st

Sam Thorogood 16 Nov 13, 2022
Command line utility to split OpenAPI documents into smaller, self contained, service oriented documents and prepare StackQL provider interfaces

openapi-doc-util Command line utility to split OpenAPI documents into smaller, self contained, service oriented documents and prepare StackQL provider

StackQL Studios 9 Sep 29, 2022
A free and open source file compression tool, Compressor makes your files smaller!

Compressor A free and open source file compression tool, Compressor makes your files smaller! Languages: ???? 中文 | ???? English Feature Internationali

五月君 100 Dec 24, 2022
An all new Titanfall VPK unpacker. Over 2x faster than the most popular alternative!

Harmony VPK Tool An electron-based app for unpacking Respawn VPK files. Super-fast and made with ♥ Why use Harmony VPK Tool over cra0's VPKTool? It's

Harmony 16 Dec 19, 2022
A faster alternative to legacy node:querystring module

fast-querystring Fast query-string parser and stringifier to replace the legacy node:querystring module. Installation npm i fast-querystring Features

Yagiz Nizipli 95 Dec 17, 2022
Material-UI is a simple and customizable component library to build faster, beautiful, and more accessible React applications. Follow your own design system, or start with Material Design.

Material-UI Quickly build beautiful React apps. Material-UI is a simple and customizable component library to build faster, beautiful, and more access

Material-UI 83.6k Dec 30, 2022
tauOS 17 Jul 10, 2022
2x times faster than chalk and use 5x less space in node_modules

Nano Colors A tiny and fast Node.js library for formatting terminal text with ANSI colors. It is 2 times faster than chalk. Both loading and calls. No

Andrey Sitnik 886 Dec 30, 2022
Ganache is an Ethereum simulator that makes developing Ethereum applications faster, easier, and safer

Ganache is an Ethereum simulator that makes developing Ethereum applications faster, easier, and safer. It includes all popular RPC functions and features (like events) and can be run deterministically to make development a breeze.

Truffle Suite 2.2k Jan 7, 2023
Cloudy is a set of constructs for the AWS Cloud Development Kit that aim to improve the DX by providing a faster and type-safe code environment.

cloudy-ts These packages aren't yet published on npm. This is still highly experimental. Need to figure out a few things before releasing the first ve

Cristian Pallarés 5 Nov 3, 2022
Bitloops is Low-Code Workflow Orchestration platform that helps you build backend systems and APIs 10x faster.

Bitloops Bitloops is a scalable open source Firebase substitute that can support any database and workflow orchestration. We’re building Bitloops usin

Bitloops 21 Aug 9, 2022
Optimized DNS/HTTP Log Tool for pentesters, faster and easy to use.

Optimized DNS/HTTP Log Tool for pentesters, faster and easy to use.

null 295 Dec 9, 2022
A JavaScript module that shortens your code, makes life easier, and makes development faster!

Quxt A JavaScript module that shortens your code, makes life easier, and makes development faster! Installation npm install quxt Quick Start Check ind

Qux App 5 May 8, 2022
Plug-and-play, faster-than-native promise/callback event emitter

kNow Blazing-fast callback/promise-based events with a tiny footprint What is this? With kNow (pronounced "now"—the k's silent), JavaScript event mana

Elijah Bodden 25 Sep 11, 2022
Mongo Strict is a TypeScript based smart MongoDB ORM, It makes the usage of MongoDB safer, easier and faster with a better performance...

mongo-strict mongo-strict is compatible with mongo >= 5 Mongo Strict is a TypeScript-based smart MongoDB ORM, It makes the usage of MongoDB safer, eas

Mohamed Kamel 4 Sep 22, 2022
Prisma is a next-generation object–relational mapper (ORM) that claims to help developers build faster and make fewer errors.

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Rhodin Emmanuel Nagwere 1 Oct 8, 2022
🎮 The only Front-End Performance Checklist that runs faster than the others

Front-End Performance Checklist ?? The only Front-End Performance Checklist that runs faster than the others. One simple rule: "Design and code with p

David Dias 15.5k Jan 1, 2023
Package manager faster than NPM

Pine Script holder that runs faster than NPM and yarn Pine is a npm and yarn run like module, that allows you to organize your scripts and run them FA

Darkling 4 Jul 10, 2021
Performant Particles: 3 to 6 times faster than tsParticles or Particles.js

perParticles Performant Particles is a demo that was written to handle a comparatively large amount of particles without slowing down to the same degr

Alaric von Teplitz 28 Oct 2, 2022
The Wholesome App. A project that allows you to upload images directly to MongoDB Atlas into your collection, a faster cloud database.

The Wholesome App. A project that allows you to upload images directly to MongoDB Atlas into your collection, a faster cloud database. To upload your cute and wholesome images.

Gourav Singh Rawat 2 Jul 17, 2022