https://selfrefactor.github.io/rambda/
Typescript focused FP library similar to Remeda and Rambda
https://selfrefactor.github.io/rambda/
fp functional functional-programming functions lodash ramda typescript utility utils
Last synced: about 1 year ago
JSON representation
Typescript focused FP library similar to Remeda and Rambda
- Host: GitHub
- URL: https://selfrefactor.github.io/rambda/
- Owner: selfrefactor
- License: mit
- Created: 2017-01-15T13:50:45.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2025-05-09T08:30:38.000Z (about 1 year ago)
- Last Synced: 2025-05-09T09:30:11.064Z (about 1 year ago)
- Topics: fp, functional, functional-programming, functions, lodash, ramda, typescript, utility, utils
- Language: JavaScript
- Homepage: https://selfrefactor.github.io/rambda/
- Size: 13.6 MB
- Stars: 1,719
- Watchers: 15
- Forks: 89
- Open Issues: 2
-
Metadata Files:
- Readme: .github/README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
- Security: SECURITY.md
Awesome Lists containing this project
- awesome-docsify - Rambda - Lightweight functional JS library. (Showcase)
README
# Rambda
`Rambda` is TypeScript-focused utility library similar to `Remeda` and `Lodash`.
Initially it started as faster alternative to functional programming library `Ramda`, but in order to address many TypeScript issues, now `Rambda` takes a separate path. - [Documentation](https://selfrefactor.github.io/rambda/#/)


[](https://packagephobia.com/result?p=rambda)
[](https://github.com/selfrefactor/rambda/pulls)
[](https://github.com/selfrefactor/rambda/graphs/contributors)
## ❯ Example use
```javascript
import { pipe, map, filter } from 'rambda'
const result = pipe(
[1, 2, 3, 4],
filter(x => x > 2),
map(x => x * 2),
)
// => [6, 8]
```
You can test this example in Rambda's REPL
* [API](#api)
* [Changelog](#-changelog)
[](#-example-use)
## ❯ Rambda's features
## ❯ Goals
### Typescript focus
Mixing `Functional Programming` and `TypeScript` is not easy.
One way to solve this is to focus what can be actually achieved and refrain from what is not possible.
### `R.pipe` as the main way to use Rambda
- All methods are meant to be used as part of `R.pipe` chain
- This is the main purpose of functional programming, i.e. to pass data through a chain of functions.
- Having `R.pipe(input, ...fns)` helps TypeScript to infer the types of the input and the output.
Here is one example why `R.pipe` is better than `Ramda.pipe`:
```ts
const list = [1, 2, 3];
it('within pipe', () => {
const result = pipe(
list,
filter((x) => {
x; // $ExpectType number
return x > 1;
}),
);
result; // $ExpectType number[]
});
it('within Ramda.pipe requires explicit types', () => {
Ramda.pipe(
(x) => x,
filter((x) => {
x; // $ExpectType number
return x > 1;
}),
filter((x: number) => {
x; // $ExpectType number
return x > 1;
}),
)(list);
});
```
### Keep only the most useful methods
The idea is to give `TypeScript` users only the most useful methods and let them implement the rest. No magic logic methods that are hard to remember. You shouldn't need to read the documentation to understand what a method does. Its name and signature should be enough.
- Methods that are simply to remember only by its name. Complex logic shouldn't be part of utility library, but part of your codebase.
- Keep only methods which are both useful and which behaviour is obvious from its name. For example, `R.innerJoin` is kept, but `R.identical`, `R.move` is removed. Methods such as `R.toLower`, `R.length` provide little value. Such method are omitted from Rambda on purpose.
- Some generic methods such as `curry` and `assoc` is not easy to be expressed in TypeScript. For this reason `Rambda` omits such methods.
- No `R.cond` or `R.ifElse` as they make the chain less readable.
- No `R.length` as it adds very little value.
- No `R.difference` as user must remember the order of the inputs, i.e. which is compared to and which is compared against.
### One way to use each method
Because of the focus on `R.pipe`, there is only one way to use each method. This helps with testing and also with TypeScript definitions.
- All methods that 2 inputs, will have to be called with `R.methodName(input1)(input2)`
- All methods that 3 inputs, will have to be called with `R.methodName(input1, input2)(input3)`
### Immutable TS definitions
You can use immutable version of Rambda definitions, which is linted with ESLint `functional/prefer-readonly-type` plugin.
```
import {filter} from 'rambda/immutable'
```
### Deno support
```
import * as R from "https://deno.land/x/rambda/mod.ts";
R.filter(x => x > 1)([1, 2, 3])
```
### Dot notation for `R.path`
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} })
```
Please note that since path input is turned into array, i.e. if you want `R.path(['a','1', 'b'])({a: {'1': {b: 2}}})` to return `2`, you will have to pass array path, not string path. If you pass `a.1.b`, it will turn path input to `['a', 1, 'b']`.
### 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
```
### Fast performance compared to Ramda
Since `Rambda` methods doesn't use so many internals, it is faster than `Ramda`.
Prior to version `10`, benchmark summary was included, but now the main selling point is the TypeScript focus, not performance so this is no longer included.
### Differences between Rambda and Ramda
Up until version `9.4.2`, the aim of Rambda was to match as much as possible the Ramda API.
Documentation site of `Rambda` version `9.4.2` is available [here](https://selfrefactor.github.io/rambda-v9/).
From version `10.0.0` onwards, Rambda will start to diverge from Ramda in order to address some of the issues that Ramda has.
Ramda issues
-- Typescript support - this is the main reason for the divergence. Most of design decisions in Rambda are made with Typescript in mind.
-- Methods that imply side-effect, which is not FP oriented, e.g. `R.forEach`.
-- Naming of methods that doesn't match developer's expectation, such as `R.chain`, which should be called `flatMap`.
-- Naming of methods is sometimes too generic to be remembered such as `R.update`, `R.modify`, `R.where`.
-- Methods that are already present in standard JavaScript, such as `R.toLower`, `R.length`.
-- `R.compose` doesn't have the best possible TypeScript support.
[](#-rambdas-features)
## API
### addProp
```typescript
addProp(
prop: P,
value: V
): (obj: T) => MergeTypes>
```
It adds new key-value pair to the object.
```javascript
const result = R.pipe(
{ a: 1, b: 'foo' },
R.addProp('c', 3)
)
// => { a: 1, b: 'foo', c: 3 }
```
Try this R.addProp example in Rambda REPL
All TypeScript definitions
```typescript
addProp(
prop: P,
value: V
): (obj: T) => MergeTypes>;
```
R.addProp source
```javascript
export function addProp(key, value) {
return obj => ({ ...obj, [key]: value })
}
```
Tests
```javascript
import { addProp } from "./addProp.js"
test('happy', () => {
const result = addProp('a', 1)({ b: 2 })
const expected = { a: 1, b: 2 }
expect(result).toEqual(expected)
})
```
TypeScript test
```typescript
import { addProp, pipe } from 'rambda'
it('R.addProp', () => {
const result = pipe({ a: 1, b: 'foo' }, addProp('c', 3))
result.a // $ExpectType number
result.b // $ExpectType string
result.c // $ExpectType number
})
```
[](#addProp)
### all
```typescript
all(predicate: (x: T) => boolean): (list: T[]) => boolean
```
It returns `true`, if all members of array `list` returns `true`, when applied as argument to `predicate` function.
```javascript
const list = [ 0, 1, 2, 3, 4 ]
const predicate = x => x > -1
const result = R.pipe(
list,
R.all(predicate)
) // => true
```
Try this R.all example in Rambda REPL
All TypeScript definitions
```typescript
all(predicate: (x: T) => boolean): (list: T[]) => boolean;
```
R.all source
```javascript
export function all(predicate) {
return list => {
for (let i = 0; i < list.length; i++) {
if (!predicate(list[i])) {
return false
}
}
return true
}
}
```
Tests
```javascript
import { all } from './all.js'
const list = [0, 1, 2, 3, 4]
test('when true', () => {
const fn = x => x > -1
expect(all(fn)(list)).toBeTruthy()
})
test('when false', () => {
const fn = x => x > 2
expect(all(fn)(list)).toBeFalsy()
})
```
TypeScript test
```typescript
import * as R from 'rambda'
describe('all', () => {
it('happy', () => {
const result = R.pipe(
[1, 2, 3],
R.all(x => {
x // $ExpectType number
return x > 0
}),
)
result // $ExpectType boolean
})
})
```
[](#all)
### allPass
```typescript
allPass boolean>(predicates: readonly F[]): F
```
It returns `true`, if all functions of `predicates` return `true`, when `input` is their argument.
```javascript
const list = [[1, 2, 3, 4], [3, 4, 5]]
const result = R.pipe(
list,
R.filter(R.allPass([R.includes(2), R.includes(3)]))
) // => [[1, 2, 3, 4]]
```
Try this R.allPass example in Rambda REPL
All TypeScript definitions
```typescript
allPass boolean>(predicates: readonly F[]): F;
```
R.allPass source
```javascript
export function allPass(predicates) {
return input => {
let counter = 0
while (counter < predicates.length) {
if (!predicates[counter](input)) {
return false
}
counter++
}
return true
}
}
```
Tests
```javascript
import { allPass } from './allPass.js'
import { filter } from './filter.js'
import { includes } from './includes.js'
import { pipe } from './pipe.js'
const list = [
[1, 2, 3, 4],
[3, 4, 5],
]
test('happy', () => {
const result = pipe(list, filter(allPass([includes(2), includes(3)])))
expect(result).toEqual([[1, 2, 3, 4]])
})
test('when returns false', () => {
const result = pipe(list, filter(allPass([includes(12), includes(31)])))
expect(result).toEqual([])
})
```
TypeScript test
```typescript
import * as R from 'rambda'
describe('allPass', () => {
it('happy', () => {
const list = [
[1, 2, 3, 4],
[3, 4, 5],
]
const result = R.pipe(list, R.map(R.allPass([R.includes(3), R.includes(4)])))
result // $ExpectType boolean[]
})
})
```
[](#allPass)
### any
```typescript
any(predicate: (x: T) => boolean): (list: T[]) => boolean
```
It returns `true`, if at least one member of `list` returns true, when passed to a `predicate` function.
```javascript
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
```typescript
any(predicate: (x: T) => boolean): (list: T[]) => boolean;
```
R.any source
```javascript
export function any(predicate) {
return list => {
let counter = 0
while (counter < list.length) {
if (predicate(list[counter], counter)) {
return true
}
counter++
}
return false
}
}
```
Tests
```javascript
import { any } from './any.js'
const list = [1, 2, 3]
test('happy', () => {
expect(any(x => x > 2)(list)).toBeTruthy()
})
```
TypeScript test
```typescript
import { any, pipe } from 'rambda'
it('R.any', () => {
const result = pipe(
[1, 2, 3],
any(x => {
x // $ExpectType number
return x > 2
}),
)
result // $ExpectType boolean
})
```
[](#any)
### anyPass
```typescript
anyPass(
predicates: [(a: T) => a is TF1, (a: T) => a is TF2],
): (a: T) => a is TF1 | TF2
```
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`.
> :boom: Function accepts only one input, but in Ramda it accepts indefinite number of arguments.
```javascript
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
```typescript
anyPass(
predicates: [(a: T) => a is TF1, (a: T) => a is TF2],
): (a: T) => a is TF1 | TF2;
anyPass(
predicates: [(a: T) => a is TF1, (a: T) => a is TF2, (a: T) => a is TF3],
): (a: T) => a is TF1 | TF2 | TF3;
anyPass(
predicates: [(a: T) => a is TF1, (a: T) => a is TF2, (a: T) => a is TF3],
): (a: T) => a is TF1 | TF2 | TF3;
anyPass(
predicates: [(a: T) => a is TF1, (a: T) => a is TF2, (a: T) => a is TF3, (a: T) => a is TF4],
): (a: T) => a is TF1 | TF2 | TF3 | TF4;
anyPass(
predicates: [
(a: T) => a is TF1,
(a: T) => a is TF2,
(a: T) => a is TF3,
(a: T) => a is TF4,
(a: T) => a is TF5
],
): (a: T) => a is TF1 | TF2 | TF3 | TF4 | TF5;
anyPass(
predicates: [
(a: T) => a is TF1,
(a: T) => a is TF2,
(a: T) => a is TF3,
(a: T) => a is TF4,
(a: T) => a is TF5,
(a: T) => a is TF6
],
): (a: T) => a is TF1 | TF2 | TF3 | TF4 | TF5 | TF6;
anyPass boolean>(predicates: readonly F[]): F;
```
R.anyPass source
```javascript
export function anyPass(predicates) {
return input => {
let counter = 0
while (counter < predicates.length) {
if (predicates[counter](input)) {
return true
}
counter++
}
return false
}
}
```
Tests
```javascript
import { anyPass } from './anyPass.js'
test('happy', () => {
const rules = [x => typeof x === 'string', x => x > 10]
const predicate = anyPass(rules)
expect(predicate('foo')).toBeTruthy()
expect(predicate(6)).toBeFalsy()
})
test('happy', () => {
const rules = [x => typeof x === 'string', x => x > 10]
expect(anyPass(rules)(11)).toBeTruthy()
expect(anyPass(rules)(undefined)).toBeFalsy()
})
const obj = {
a: 1,
b: 2,
}
test('when returns true', () => {
const conditionArr = [val => val.a === 1, val => val.a === 2]
expect(anyPass(conditionArr)(obj)).toBeTruthy()
})
test('when returns false', () => {
const conditionArr = [val => val.a === 2, val => val.b === 3]
expect(anyPass(conditionArr)(obj)).toBeFalsy()
})
test('with empty predicates list', () => {
expect(anyPass([])(3)).toBeFalsy()
})
```
TypeScript test
```typescript
import { anyPass, filter } from 'rambda'
describe('anyPass', () => {
it('issue #604', () => {
const plusEq = (w: number, x: number, y: number, z: number) => w + x === y + z
const result = anyPass([plusEq])(3, 3, 3, 3)
result // $ExpectType boolean
})
it('issue #642', () => {
const isGreater = (num: number) => num > 5
const pred = anyPass([isGreater])
const xs = [0, 1, 2, 3]
const filtered1 = filter(pred)(xs)
filtered1 // $ExpectType number[]
const filtered2 = xs.filter(pred)
filtered2 // $ExpectType number[]
})
it('functions as a type guard', () => {
const isString = (x: unknown): x is string => typeof x === 'string'
const isNumber = (x: unknown): x is number => typeof x === 'number'
const isBoolean = (x: unknown): x is boolean => typeof x === 'boolean'
const isStringNumberOrBoolean = anyPass([isString, isNumber, isBoolean])
const aValue: unknown = 1
if (isStringNumberOrBoolean(aValue)) {
aValue // $ExpectType string | number | boolean
}
})
})
```
[](#anyPass)
### append
```typescript
append(el: T): (list: T[]) => T[]
```
It adds element `x` at the end of `iterable`.
```javascript
const x = 'foo'
const result = R.append(x, ['bar', 'baz'])
// => ['bar', 'baz', 'foo']
```
Try this R.append example in Rambda REPL
All TypeScript definitions
```typescript
append(el: T): (list: T[]) => T[];
append(el: T): (list: readonly T[]) => T[];
```
R.append source
```javascript
import { cloneList } from './_internals/cloneList.js'
export function append(x) {
return list => {
const clone = cloneList(list)
clone.push(x)
return clone
}
}
```
Tests
```javascript
import { append } from './append.js'
test('happy', () => {
expect(append('tests')(['write', 'more'])).toEqual(['write', 'more', 'tests'])
})
test('append to empty array', () => {
expect(append('tests')([])).toEqual(['tests'])
})
```
TypeScript test
```typescript
import { append, pipe, prepend } from 'rambda'
const listOfNumbers = [1, 2, 3]
describe('R.append/R.prepend', () => {
it('happy', () => {
const result = pipe(listOfNumbers, append(4), prepend(0))
result // $ExpectType number[]
})
it('with object', () => {
const result = pipe([{ a: 1 }], append({ a: 10 }), prepend({ a: 20 }))
result // $ExpectType { a: number; }[]
})
})
```
[](#append)
### ascend
Helper function to be used with `R.sort` to sort list in ascending order.
```javascript
const result = R.pipe(
[{a: 1}, {a: 2}, {a: 0}],
R.sort(R.ascend(R.prop('a')))
)
// => [{a: 0}, {a: 1}, {a: 2}]
```
Try this R.ascend example in Rambda REPL
[](#ascend)
### checkObjectWithSpec
```typescript
checkObjectWithSpec(spec: T): (testObj: U) => boolean
```
It returns `true` if all each property in `conditions` returns `true` when applied to corresponding property in `input` object.
```javascript
const condition = R.checkObjectWithSpec({
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.checkObjectWithSpec example in Rambda REPL
All TypeScript definitions
```typescript
checkObjectWithSpec(spec: T): (testObj: U) => boolean;
```
R.checkObjectWithSpec source
```javascript
export function checkObjectWithSpec(conditions) {
return input => {
let shouldProceed = true
for (const prop in conditions) {
if (!shouldProceed) {
continue
}
const result = conditions[prop](input[prop])
if (shouldProceed && result === false) {
shouldProceed = false
}
}
return shouldProceed
}
}
```
Tests
```javascript
import { checkObjectWithSpec } from './checkObjectWithSpec.js'
import { equals } from './equals.js'
test('when true', () => {
const result = checkObjectWithSpec({
a: equals('foo'),
b: equals('bar'),
})({
a: 'foo',
b: 'bar',
x: 11,
y: 19,
})
expect(result).toBeTruthy()
})
test('when false | early exit', () => {
let counter = 0
const equalsFn = expected => input => {
counter++
return input === expected
}
const predicate = checkObjectWithSpec({
a: equalsFn('foo'),
b: equalsFn('baz'),
})
expect(
predicate({
a: 'notfoo',
b: 'notbar',
}),
).toBeFalsy()
expect(counter).toBe(1)
})
```
TypeScript test
```typescript
import { checkObjectWithSpec, equals } from 'rambda'
describe('R.checkObjectWithSpec', () => {
it('happy', () => {
const input = {
a: 'foo',
b: 'bar',
x: 11,
y: 19,
}
const conditions = {
a: equals('foo'),
b: equals('bar'),
}
const result = checkObjectWithSpec(conditions)(input)
result // $ExpectType boolean
})
})
```
[](#checkObjectWithSpec)
### compact
```typescript
compact(list: T[]): Array>
```
It removes `null` and `undefined` members from list or object input.
```javascript
const result = R.pipe(
{
a: [ undefined, '', 'a', 'b', 'c'],
b: [1,2, null, 0, undefined, 3],
c: { a: 1, b: 2, c: 0, d: undefined, e: null, f: false },
},
x => ({
a: R.compact(x.a),
b: R.compact(x.b),
c: R.compact(x.c)
})
)
// => { a: ['a', 'b', 'c'], b: [1, 2, 3], c: { a: 1, b: 2, c: 0, f: false } }
```
Try this R.compact example in Rambda REPL
All TypeScript definitions
```typescript
compact(list: T[]): Array>;
compact(record: T): {
[K in keyof T as Exclude extends never
? never
: K
]: Exclude
};
```
R.compact source
```javascript
import { isArray } from './_internals/isArray.js'
import { reject } from './reject.js'
import { rejectObject } from './rejectObject.js'
const isNullOrUndefined = x => x === null || x === undefined
export function compact(input){
if(isArray(input)){
return reject(isNullOrUndefined)(input)
}
return rejectObject(isNullOrUndefined)(input)
}
```
Tests
```javascript
import { compact } from './compact.js'
import { pipe } from './pipe.js'
test('happy', () => {
const result = pipe(
{
a: [ undefined, 'a', 'b', 'c'],
b: [1,2, null, 0, undefined, 3],
c: { a: 1, b: 2, c: 0, d: undefined, e: null, f: false },
},
x => ({
a: compact(x.a),
b: compact(x.b),
c: compact(x.c)
})
)
expect(result.a).toEqual(['a', 'b', 'c'])
expect(result.b).toEqual([1,2,0,3])
expect(result.c).toEqual({ a: 1, b: 2,c:0, f: false })
})
```
TypeScript test
```typescript
import { compact, pipe } from 'rambda'
it('R.compact', () => {
let result = pipe(
{
a: [ undefined, '', 'a', 'b', 'c', null ],
b: [1,2, null, 0, undefined, 3],
c: { a: 1, b: 2, c: 0, d: undefined, e: null, f: false },
},
x => ({
a: compact(x.a),
b: compact(x.b),
c: compact(x.c)
})
)
result.a // $ExpectType string[]
result.b // $ExpectType number[]
result.c // $ExpectType { a: number; b: number; c: number; f: boolean; }
})
```
[](#compact)
### complement
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)`.
```javascript
const fn = x => x > 5
const inverted = complement(fn)
const result = [
fn(7),
inverted(7)
] => [ true, false ]
```
Try this R.complement example in Rambda REPL
[](#complement)
### concat
It returns a new string or array, which is the result of merging `x` and `y`.
```javascript
R.concat([1, 2])([3, 4]) // => [1, 2, 3, 4]
R.concat('foo')('bar') // => 'foobar'
```
Try this R.concat example in Rambda REPL
[](#concat)
### count
It counts how many times `predicate` function returns `true`, when supplied with iteration of `list`.
```javascript
const list = [{a: 1}, 1, {a:2}]
const result = R.count(x => x.a !== undefined)(list)
// => 2
```
Try this R.count example in Rambda REPL
[](#count)
### countBy
```typescript
countBy(fn: (x: T) => string | number): (list: T[]) => { [index: string]: number }
```
It counts elements in a list after each instance of the input list is passed through `transformFn` function.
```javascript
const list = [ 'a', 'A', 'b', 'B', 'c', 'C' ]
const result = countBy(x => x.toLowerCase())( list)
const expected = { a: 2, b: 2, c: 2 }
// => `result` is equal to `expected`
```
Try this R.countBy example in Rambda REPL
All TypeScript definitions
```typescript
countBy(fn: (x: T) => string | number): (list: T[]) => { [index: string]: number };
```
R.countBy source
```javascript
export function countBy(fn) {
return list => {
const willReturn = {}
list.forEach(item => {
const key = fn(item)
if (!willReturn[key]) {
willReturn[key] = 1
} else {
willReturn[key]++
}
})
return willReturn
}
}
```
Tests
```javascript
import { countBy } from './countBy.js'
const list = ['a', 'A', 'b', 'B', 'c', 'C']
test('happy', () => {
const result = countBy(x => x.toLowerCase())(list)
expect(result).toEqual({
a: 2,
b: 2,
c: 2,
})
})
```
TypeScript test
```typescript
import { countBy, pipe } from 'rambda'
const list = ['a', 'A', 'b', 'B', 'c', 'C']
it('R.countBy', () => {
const result = pipe(
list,
countBy(x => x.toLowerCase()),
)
result.a // $ExpectType number
result.foo // $ExpectType number
result // $ExpectType { [index: string]: number; }
})
```
[](#countBy)
### createObjectFromKeys
```typescript
createObjectFromKeys(
fn: (key: K[number]) => V
): (keys: K) => { [P in K[number]]: V }
```
```javascript
const result = R.createObjectFromKeys(
(x, index) => `${x}-${index}`
)(['a', 'b', 'c'])
// => {a: 'a-0', b: 'b-1', c: 'c-2'}
```
Try this R.createObjectFromKeys example in Rambda REPL
All TypeScript definitions
```typescript
createObjectFromKeys(
fn: (key: K[number]) => V
): (keys: K) => { [P in K[number]]: V };
createObjectFromKeys(
fn: (key: K[number], index: number) => V
): (keys: K) => { [P in K[number]]: V };
```
R.createObjectFromKeys source
```javascript
export function createObjectFromKeys(keys) {
return fn => {
const result = {}
keys.forEach((key, index) => {
result[key] = fn(key, index)
})
return result
}
}
```
Tests
```javascript
import { createObjectFromKeys } from './createObjectFromKeys.js'
test('happy', () => {
const result = createObjectFromKeys(['a', 'b'])((key, index) => key.toUpperCase() + index)
const expected = { a: 'A0', b: 'B1' }
expect(result).toEqual(expected)
})
```
[](#createObjectFromKeys)
### defaultTo
```typescript
defaultTo(defaultValue: T): (input: unknown) => 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).
> :boom: Typescript Note: Pass explicit type annotation when used with **R.pipe/R.compose** for better type inference
```javascript
R.defaultTo('foo')('bar') // => 'bar'
R.defaultTo('foo'))(undefined) // => 'foo'
// Important - emtpy string is not falsy value
R.defaultTo('foo')('') // => 'foo'
```
Try this R.defaultTo example in Rambda REPL
All TypeScript definitions
```typescript
defaultTo(defaultValue: T): (input: unknown) => T;
```
R.defaultTo source
```javascript
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
```javascript
import { defaultTo } from './defaultTo.js'
test('with undefined', () => {
expect(defaultTo('foo')(undefined)).toBe('foo')
})
test('with null', () => {
expect(defaultTo('foo')(null)).toBe('foo')
})
test('with NaN', () => {
expect(defaultTo('foo')(Number.NaN)).toBe('foo')
})
test('with empty string', () => {
expect(defaultTo('foo', '')).toBe('')
})
test('with false', () => {
expect(defaultTo('foo', false)).toBeFalsy()
})
test('when inputArgument passes initial check', () => {
expect(defaultTo('foo', 'bar')).toBe('bar')
})
```
TypeScript test
```typescript
import { defaultTo, pipe } from 'rambda'
describe('R.defaultTo', () => {
it('happy', () => {
const result = pipe('bar' as unknown, defaultTo('foo'))
result // $ExpectType string
})
})
```
[](#defaultTo)
### descend
Helper function to be used with `R.sort` to sort list in descending order.
```javascript
const result = R.pipe(
[{a: 1}, {a: 2}, {a: 0}],
R.sort(R.descend(R.prop('a')))
)
// => [{a: 2}, {a: 1}, {a: 0}]
```
Try this R.descend example in Rambda REPL
[](#descend)
### drop
```typescript
drop(howMany: number): (list: T[]) => T[]
```
It returns `howMany` items dropped from beginning of list.
```javascript
R.drop(2)(['foo', 'bar', 'baz']) // => ['baz']
```
Try this R.drop example in Rambda REPL
All TypeScript definitions
```typescript
drop(howMany: number): (list: T[]) => T[];
```
R.drop source
```javascript
export function drop(howManyToDrop, listOrString) {
if (arguments.length === 1) {
return _list => drop(howManyToDrop, _list)
}
return listOrString.slice(howManyToDrop > 0 ? howManyToDrop : 0)
}
```
Tests
```javascript
import assert from 'node:assert'
import { drop } from './drop.js'
test('with array', () => {
expect(drop(2)(['foo', 'bar', 'baz'])).toEqual(['baz'])
expect(drop(3, ['foo', 'bar', 'baz'])).toEqual([])
expect(drop(4, ['foo', 'bar', 'baz'])).toEqual([])
})
test('with string', () => {
expect(drop(3, 'rambda')).toBe('bda')
})
test('with non-positive count', () => {
expect(drop(0, [1, 2, 3])).toEqual([1, 2, 3])
expect(drop(-1, [1, 2, 3])).toEqual([1, 2, 3])
expect(drop(Number.NEGATIVE_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
```typescript
import { drop, pipe } from 'rambda'
it('R.drop', () => {
const result = pipe([1, 2, 3, 4], drop(2))
result // $ExpectType number[]
})
```
[](#drop)
### dropLast
```typescript
dropLast(howMany: number): (list: T[]) => T[]
```
It returns `howMany` items dropped from the end of list.
All TypeScript definitions
```typescript
dropLast(howMany: number): (list: T[]) => T[];
```
R.dropLast source
```javascript
export function dropLast(numberItems) {
return list => (numberItems > 0 ? list.slice(0, -numberItems) : list.slice())
}
```
Tests
```javascript
import { dropLast } from './dropLast.js'
test('with array', () => {
expect(dropLast(2)(['foo', 'bar', 'baz'])).toEqual(['foo'])
expect(dropLast(3)(['foo', 'bar', 'baz'])).toEqual([])
expect(dropLast(4)(['foo', 'bar', 'baz'])).toEqual([])
})
test('with 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(Number.NEGATIVE_INFINITY)([1, 2, 3])).toEqual([1, 2, 3])
})
```
[](#dropLast)
### dropLastWhile
```javascript
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
[](#dropLastWhile)
### dropRepeatsBy
```javascript
const result = R.dropRepeatsBy(
Math.abs,
[1, -1, 2, 3, -3]
)
// => [1, 2, 3]
```
Try this R.dropRepeatsBy example in Rambda REPL
[](#dropRepeatsBy)
### dropRepeatsWith
```javascript
const list = [{a:1,b:2}, {a:1,b:3}, {a:2, b:4}]
const result = R.dropRepeatsWith(R.prop('a'))(list)
// => [{a:1,b:2}, {a:2, b:4}]
```
Try this R.dropRepeatsWith example in Rambda REPL
[](#dropRepeatsWith)
### dropWhile
```javascript
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
[](#dropWhile)
### eqBy
```javascript
const result = R.eqBy(Math.abs, 5)(-5)
// => true
```
Try this R.eqBy example in Rambda REPL
[](#eqBy)
### eqProps
It returns `true` if property `prop` in `obj1` is equal to property `prop` in `obj2` according to `R.equals`.
```javascript
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
[](#eqProps)
### equals
```typescript
equals(x: T, y: T): boolean
```
It deeply compares `x` and `y` and returns `true` if they are equal.
> :boom: It doesn't handle cyclical data structures and functions
```javascript
R.equals(
[1, {a:2}, [{b: 3}]],
[1, {a:2}, [{b: 3}]]
) // => true
```
Try this R.equals example in Rambda REPL
All TypeScript definitions
```typescript
equals(x: T, y: T): boolean;
equals(x: T): (y: T) => boolean;
```
R.equals source
```javascript
import { isArray } from './_internals/isArray.js'
import { type } from './type.js'
export function _lastIndexOf(valueToFind, list) {
if (!isArray(list)) {
throw new Error(`Cannot read property 'indexOf' of ${list}`)
}
const typeOfValue = type(valueToFind)
if (!['Array', 'NaN', 'Object', 'RegExp'].includes(typeOfValue)) {
return list.lastIndexOf(valueToFind)
}
const { length } = list
let index = length
let foundIndex = -1
while (--index > -1 && foundIndex === -1) {
if (equalsFn(list[index], valueToFind)) {
foundIndex = index
}
}
return foundIndex
}
export function _indexOf(valueToFind, list) {
if (!isArray(list)) {
throw new Error(`Cannot read property 'indexOf' of ${list}`)
}
const typeOfValue = type(valueToFind)
if (!['Array', 'NaN', 'Object', 'RegExp'].includes(typeOfValue)) {
return list.indexOf(valueToFind)
}
let index = -1
let foundIndex = -1
const { length } = list
while (++index < length && foundIndex === -1) {
if (equalsFn(list[index], valueToFind)) {
foundIndex = index
}
}
return foundIndex
}
function _arrayFromIterator(iter) {
const list = []
let next
while (!(next = iter.next()).done) {
list.push(next.value)
}
return list
}
function _compareSets(a, b) {
if (a.size !== b.size) {
return false
}
const aList = _arrayFromIterator(a.values())
const bList = _arrayFromIterator(b.values())
const filtered = aList.filter(aInstance => _indexOf(aInstance, bList) === -1)
return filtered.length === 0
}
function compareErrors(a, b) {
if (a.message !== b.message) {
return false
}
if (a.toString !== b.toString) {
return false
}
return a.toString() === b.toString()
}
function parseDate(maybeDate) {
if (!maybeDate.toDateString) {
return [false]
}
return [true, maybeDate.getTime()]
}
function parseRegex(maybeRegex) {
if (maybeRegex.constructor !== RegExp) {
return [false]
}
return [true, maybeRegex.toString()]
}
export function equalsFn(a, b) {
if (Object.is(a, b)) {
return true
}
const aType = type(a)
if (aType !== type(b)) {
return false
}
if (aType === 'Function') {
return a.name === undefined ? false : a.name === b.name
}
if (['NaN', 'Null', 'Undefined'].includes(aType)) {
return true
}
if (['BigInt', 'Number'].includes(aType)) {
if (Object.is(-0, a) !== Object.is(-0, b)) {
return false
}
return a.toString() === b.toString()
}
if (['Boolean', 'String'].includes(aType)) {
return a.toString() === b.toString()
}
if (aType === 'Array') {
const aClone = Array.from(a)
const bClone = Array.from(b)
if (aClone.toString() !== bClone.toString()) {
return false
}
let loopArrayFlag = true
aClone.forEach((aCloneInstance, aCloneIndex) => {
if (loopArrayFlag) {
if (
aCloneInstance !== bClone[aCloneIndex] &&
!equalsFn(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
}
if (bRegex[0]) {
return false
}
const aDate = parseDate(a)
const bDate = parseDate(b)
if (aDate[0]) {
return bDate[0] ? aDate[1] === bDate[1] : false
}
if (bDate[0]) {
return false
}
if (a instanceof Error) {
if (!(b instanceof Error)) {
return false
}
return compareErrors(a, b)
}
if (aType === 'Set') {
return _compareSets(a, b)
}
if (aType === 'Object') {
const aKeys = Object.keys(a)
if (aKeys.length !== Object.keys(b).length) {
return false
}
let loopObjectFlag = true
aKeys.forEach(aKeyInstance => {
if (loopObjectFlag) {
const aValue = a[aKeyInstance]
const bValue = b[aKeyInstance]
if (aValue !== bValue && !equalsFn(aValue, bValue)) {
loopObjectFlag = false
}
}
})
return loopObjectFlag
}
return false
}
export function equals(a) {
return b => equalsFn(a, b)
}
```
Tests
```javascript
import { equalsFn } from './equals.js'
test('compare functions', () => {
function foo() {}
function bar() {}
const baz = () => {}
const expectTrue = equalsFn(foo, foo)
const expectFalseFirst = equalsFn(foo, bar)
const expectFalseSecond = equalsFn(foo, baz)
expect(expectTrue).toBeTruthy()
expect(expectFalseFirst).toBeFalsy()
expect(expectFalseSecond).toBeFalsy()
})
test('with array of objects', () => {
const list1 = [{ a: 1 }, [{ b: 2 }]]
const list2 = [{ a: 1 }, [{ b: 2 }]]
const list3 = [{ a: 1 }, [{ b: 3 }]]
expect(equalsFn(list1, list2)).toBeTruthy()
expect(equalsFn(list1, list3)).toBeFalsy()
})
test('with regex', () => {
expect(equalsFn(/s/, /s/)).toBeTruthy()
expect(equalsFn(/s/, /d/)).toBeFalsy()
expect(equalsFn(/a/gi, /a/gi)).toBeTruthy()
expect(equalsFn(/a/gim, /a/gim)).toBeTruthy()
expect(equalsFn(/a/gi, /a/i)).toBeFalsy()
})
test('not a number', () => {
expect(equalsFn([Number.NaN], [Number.NaN])).toBeTruthy()
})
test('new number', () => {
expect(equalsFn(new Number(0), new Number(0))).toBeTruthy()
expect(equalsFn(new Number(0), new Number(1))).toBeFalsy()
expect(equalsFn(new Number(1), new Number(0))).toBeFalsy()
})
test('new string', () => {
expect(equalsFn(new String(''), new String(''))).toBeTruthy()
expect(equalsFn(new String(''), new String('x'))).toBeFalsy()
expect(equalsFn(new String('x'), new String(''))).toBeFalsy()
expect(equalsFn(new String('foo'), new String('foo'))).toBeTruthy()
expect(equalsFn(new String('foo'), new String('bar'))).toBeFalsy()
expect(equalsFn(new String('bar'), new String('foo'))).toBeFalsy()
})
test('new Boolean', () => {
expect(equalsFn(new Boolean(true), new Boolean(true))).toBeTruthy()
expect(equalsFn(new Boolean(false), new Boolean(false))).toBeTruthy()
expect(equalsFn(new Boolean(true), new Boolean(false))).toBeFalsy()
expect(equalsFn(new Boolean(false), new Boolean(true))).toBeFalsy()
})
test('new Error', () => {
expect(equalsFn(new Error('XXX'), {})).toBeFalsy()
expect(equalsFn(new Error('XXX'), new TypeError('XXX'))).toBeFalsy()
expect(equalsFn(new Error('XXX'), new Error('YYY'))).toBeFalsy()
expect(equalsFn(new Error('XXX'), new Error('XXX'))).toBeTruthy()
expect(equalsFn(new Error('XXX'), new TypeError('YYY'))).toBeFalsy()
expect(equalsFn(new Error('XXX'), new Error('XXX'))).toBeTruthy()
})
test('with dates', () => {
expect(equalsFn(new Date(0), new Date(0))).toBeTruthy()
expect(equalsFn(new Date(1), new Date(1))).toBeTruthy()
expect(equalsFn(new Date(0), new Date(1))).toBeFalsy()
expect(equalsFn(new Date(1), new Date(0))).toBeFalsy()
expect(equalsFn(new Date(0), {})).toBeFalsy()
expect(equalsFn({}, new Date(0))).toBeFalsy()
})
test('ramda spec', () => {
expect(equalsFn({}, {})).toBeTruthy()
expect(
equalsFn(
{
a: 1,
b: 2,
},
{
a: 1,
b: 2,
},
),
).toBeTruthy()
expect(
equalsFn(
{
a: 2,
b: 3,
},
{
a: 2,
b: 3,
},
),
).toBeTruthy()
expect(
equalsFn(
{
a: 2,
b: 3,
},
{
a: 3,
b: 3,
},
),
).toBeFalsy()
expect(
equalsFn(
{
a: 2,
b: 3,
c: 1,
},
{
a: 2,
b: 3,
},
),
).toBeFalsy()
})
test('works with boolean tuple', () => {
expect(equalsFn([true, false], [true, false])).toBeTruthy()
expect(equalsFn([true, false], [true, true])).toBeFalsy()
})
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(equalsFn(x, y)).toBeTruthy()
})
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(equalsFn(x, y)).toBeFalsy()
})
test('works with undefined as second argument', () => {
expect(equalsFn(1, undefined)).toBeFalsy()
expect(equalsFn(undefined, undefined)).toBeTruthy()
})
test('compare sets', () => {
const toCompareDifferent = new Set([{ a: 1 }, { a: 2 }])
const toCompareSame = new Set([{ a: 1 }, { a: 2 }, { a: 1 }])
const testSet = new Set([{ a: 1 }, { a: 2 }, { a: 1 }])
expect(equalsFn(toCompareSame, testSet)).toBeTruthy()
expect(equalsFn(toCompareDifferent, testSet)).toBeFalsy()
})
test('compare simple sets', () => {
const testSet = new Set(['2', '3', '3', '2', '1'])
expect(equalsFn(new Set(['3', '2', '1']), testSet)).toBeTruthy()
expect(equalsFn(new Set(['3', '2', '0']), testSet)).toBeFalsy()
})
test('various examples', () => {
expect(equalsFn([1, 2, 3], [1, 2, 3])).toBeTruthy()
expect(equalsFn([1, 2, 3], [1, 2])).toBeFalsy()
expect(equalsFn({}, {})).toBeTruthy()
})
```
TypeScript test
```typescript
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
})
})
```
[](#equals)
### evolve
```typescript
evolve(rules: {
[K in keyof T]?: (x: T[K]) => T[K]
}): (obj: T) => T
```
It takes object of functions as set of rules. These `rules` are applied to the `iterable` input to produce the result.
It doesn't support nested rules, i.e rules are only one level deep.
```javascript
const input = {
foo: 2,
baz: 'baz',
}
const result = R.pipe(
input,
evolve({
foo: x => x + 1,
})
)
// => result is { foo: 3, baz: 'baz' }
```
Try this R.evolve example in Rambda REPL
All TypeScript definitions
```typescript
evolve(rules: {
[K in keyof T]?: (x: T[K]) => T[K]
}): (obj: T) => T;
```
R.evolve source
```javascript
import { mapObject } from './mapObject.js'
import { type } from './type.js'
export function evolve(rules) {
return mapObject((x, prop) => type(rules[prop]) === 'Function' ? rules[prop](x): x)
}
```
Tests
```javascript
import { evolve } from './evolve.js'
test('happy', () => {
const rules = {
foo: x => x + 1,
}
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 } },
})
})
```
TypeScript test
```typescript
import { evolve, pipe } from 'rambda'
it('R.evolve', () => {
const input = {
baz: 1,
foo: 2,
nested: {
a: 1,
bar: 3,
},
}
const result = pipe(input,
evolve({
foo: x => x + 1,
})
)
result.foo // $ExpectType number
result.baz // $ExpectType number
result.nested.a // $ExpectType number
})
```
[](#evolve)
### excludes
Opposite of `R.includes`
`R.equals` is used to determine equality.
```javascript
const result = [
R.excludes('ar')('foo'),
R.excludes({a: 2})([{a: 1}])
]
// => [true, true ]
```
Try this R.excludes example in Rambda REPL
[](#excludes)
### filter
```typescript
filter(
predicate: (value: T) => value is S,
): (list: T[]) => S[]
```
It filters list or object `input` using a `predicate` function.
```javascript
const predicate = x => x > 1
const list = [1, 2, 3]
const result = R.filter(predicate)(list)
// => [2, 3]
```
Try this R.filter example in Rambda REPL
All TypeScript definitions
```typescript
filter(
predicate: (value: T) => value is S,
): (list: T[]) => S[];
filter(
predicate: BooleanConstructor,
): (list: readonly T[]) => StrictNonNullable[];
filter(
predicate: BooleanConstructor,
): (list: T[]) => StrictNonNullable[];
filter(
predicate: (value: T) => boolean,
): (list: T[]) => T[];
```
R.filter source
```javascript
export function filter(predicate) {
return list => {
if (!list) {
throw new Error('Incorrect iterable input')
}
let index = 0
const len = list.length
const willReturn = []
while (index < len) {
if (predicate(list[index], index)) {
willReturn.push(list[index])
}
index++
}
return willReturn
}
}
```
Tests
```javascript
import { filter } from './filter.js'
test('happy', () => {
const isEven = n => n % 2 === 0
expect(filter(isEven)([1, 2, 3, 4])).toEqual([2, 4])
})
```
TypeScript test
```typescript
import { filter, mergeTypes, pipe } from 'rambda'
const list = [1, 2, 3]
describe('R.filter with array', () => {
it('within pipe', () => {
const result = pipe(
list,
filter(x => {
x // $ExpectType number
return x > 1
}),
)
result // $ExpectType number[]
})
it('narrowing type', () => {
interface Foo {
a: number
}
interface Bar extends Foo {
b: string
}
type T = Foo | Bar
const testList: T[]= [{ a: 1 }, { a: 2 }, { a: 3 }]
const filterBar = (x: T): x is Bar => {
return typeof (x as Bar).b === 'string'
}
const result = pipe(
testList,
filter(filterBar),
)
result // $ExpectType Bar[]
})
it('narrowing type - readonly', () => {
interface Foo {
a: number
}
interface Bar extends Foo {
b: string
}
type T = Foo | Bar
const testList: T[]= [{ a: 1 }, { a: 2 }, { a: 3 }] as const
const filterBar = (x: T): x is Bar => {
return typeof (x as Bar).b === 'string'
}
const result = pipe(
testList,
filter(filterBar),
)
result // $ExpectType Bar[]
})
it('filtering NonNullable', () => {
const testList = [1, 2, null, undefined, 3]
const result = pipe(testList, filter(Boolean))
result // $ExpectType number[]
})
it('filtering NonNullable - readonly', () => {
const testList = [1, 2, null, undefined, 3] as const
const result = pipe(testList, filter(Boolean))
result.includes(1)
// @ts-expect-error
result.includes(4)
// @ts-expect-error
result.includes(undefined)
// @ts-expect-error
result.includes(null)
})
})
```
[](#filter)
### filterObject
```typescript
filterObject(
valueMapper: (
value: EnumerableStringKeyedValueOf,
key: EnumerableStringKeyOf,
data: T,
) => boolean,
): (data: T) => U
```
It loops over each property of `obj` and returns a new object with only those properties that satisfy the `predicate`.
```javascript
const result = R.filterObject(
(val, prop) => prop === 'a' || val > 1
)({a: 1, b: 2, c:3})
// => {a: 1, c: 3}
```
Try this R.filterObject example in Rambda REPL
All TypeScript definitions
```typescript
filterObject(
valueMapper: (
value: EnumerableStringKeyedValueOf,
key: EnumerableStringKeyOf,
data: T,
) => boolean,
): (data: T) => U;
```
R.filterObject source
```javascript
export function filterObject(predicate) {
return obj => {
const willReturn = {}
for (const prop in obj) {
if (predicate(obj[prop], prop, obj)) {
willReturn[prop] = obj[prop]
}
}
return willReturn
}
}
```
Tests
```javascript
import { pipe } from './pipe.js'
import { filterObject } from './filterObject.js'
test('happy', () => {
let testInput = { a: 1, b: 2, c: 3 }
const result = pipe(
testInput,
filterObject((x, prop, obj) => {
expect(prop).toBeOneOf(['a', 'b', 'c'])
expect(obj).toBe(testInput)
return x > 1
})
)
expect(result).toEqual({ b: 2, c: 3 })
})
```
TypeScript test
```typescript
import { filterObject, pipe } from 'rambda'
describe('R.filterObject', () => {
it('require explicit type', () => {
const result = pipe(
{ a: 1, b: 2 },
filterObject<{ b: number }>(a => {
a // $ExpectType number
return a > 1
}),
)
result.b // $ExpectType number
})
})
```
[](#filterObject)
### find
```typescript
find(predicate: (x: T) => boolean): (list: T[]) => T | undefined
```
It returns the first element of `list` that satisfy the `predicate`.
If there is no such element, it returns `undefined`.
```javascript
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
```typescript
find(predicate: (x: T) => boolean): (list: T[]) => T | undefined;
```
R.find source
```javascript
export function find(predicate) {
return list => {
let index = 0
const len = list.length
while (index < len) {
const x = list[index]
if (predicate(x)) {
return x
}
index++
}
}
}
```
Tests
```javascript
import { find } from './find.js'
import { propEq } from './propEq.js'
const list = [{ a: 1 }, { a: 2 }, { a: 3 }]
test('happy', () => {
const fn = propEq(2, 'a')
expect(find(fn)(list)).toEqual({ a: 2 })
})
test('nothing is found', () => {
const fn = propEq(4, 'a')
expect(find(fn)(list)).toBeUndefined()
})
test('with empty list', () => {
expect(find(() => true)([])).toBeUndefined()
})
```
TypeScript test
```typescript
import { find, pipe } from 'rambda'
const list = [1, 2, 3]
describe('R.find', () => {
it('happy', () => {
const predicate = (x: number) => x > 2
const result = pipe(list, find(predicate))
result // $ExpectType number | undefined
})
})
```
[](#find)
### findIndex
```typescript
findIndex(predicate: (x: T) => boolean): (list: T[]) => number
```
It returns the index of the first element of `list` satisfying the `predicate` function.
If there is no such element, then `-1` is returned.
```javascript
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
```typescript
findIndex(predicate: (x: T) => boolean): (list: T[]) => number;
```
R.findIndex source
```javascript
export function findIndex(predicate) {
return list => {
const len = list.length
let index = -1
while (++index < len) {
if (predicate(list[index])) {
return index
}
}
return -1
}
}
```
Tests
```javascript
import { findIndex } from './findIndex.js'
import { propEq } from './propEq.js'
const list = [{ a: 1 }, { a: 2 }, { a: 3 }]
test('happy', () => {
expect(findIndex(propEq(2, 'a'))(list)).toBe(1)
expect(findIndex(propEq(1, 'a'))(list)).toBe(0)
expect(findIndex(propEq(4, 'a'))(list)).toBe(-1)
})
```
TypeScript test
```typescript
import { findIndex, pipe } from 'rambda'
const list = [1, 2, 3]
it('R.findIndex', () => {
const result = pipe(
list,
findIndex(x => x > 2),
)
result // $ExpectType number
})
```
[](#findIndex)
### findLast
```typescript
findLast(fn: (x: T) => boolean): (list: T[]) => T | undefined
```
It returns the last element of `list` satisfying the `predicate` function.
If there is no such element, then `undefined` is returned.
```javascript
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
```typescript
findLast(fn: (x: T) => boolean): (list: T[]) => T | undefined;
```
R.findLast source
```javascript
export function findLast(predicate) {
return list => {
let index = list.length
while (--index >= 0) {
if (predicate(list[index])) {
return list[index]
}
}
return undefined
}
}
```
[](#findLast)
### findLastIndex
```typescript
findLastIndex(predicate: (x: T) => boolean): (list: T[]) => number
```
It returns the index of the last element of `list` satisfying the `predicate` function.
If there is no such element, then `-1` is returned.
```javascript
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
```typescript
findLastIndex(predicate: (x: T) => boolean): (list: T[]) => number;
```
R.findLastIndex source
```javascript
export function findLastIndex(fn) {
return list => {
let index = list.length
while (--index >= 0) {
if (fn(list[index])) {
return index
}
}
return -1
}
}
```
Tests
```javascript
import { findLastIndex } from './findLastIndex.js'
test('happy', () => {
const result = findLastIndex(x => x > 1)([1, 1, 1, 2, 3, 4, 1])
expect(result).toBe(5)
expect(findLastIndex(x => x === 0)([0, 1, 1, 2, 3, 4, 1])).toBe(0)
})
```
TypeScript test
```typescript
import { findLastIndex, pipe } from 'rambda'
const list = [1, 2, 3]
describe('R.findLastIndex', () => {
it('happy', () => {
const predicate = (x: number) => x > 2
const result = pipe(list, findLastIndex(predicate))
result // $ExpectType number
})
})
```
[](#findLastIndex)
### findNth
```typescript
findNth(predicate: (x: T) => boolean, nth: number): (list: T[]) => T | undefined
```
It returns the `nth` element of `list` that satisfy the `predicate` function.
```javascript
const predicate = x => R.type(x.foo) === 'Number'
const list = [{foo: 0}, {foo: 1}, {foo: 2}, {foo: 3}]
const result = R.findNth(predicate, 2)(list)
// => {foo: 2}
```
Try this R.findNth example in Rambda REPL
All TypeScript definitions
```typescript
findNth(predicate: (x: T) => boolean, nth: number): (list: T[]) => T | undefined;
```
R.findNth source
```javascript
export function findNth(predicate, nth) {
return list => {
let index = 0
const len = list.length
while (index < len) {
const x = list[index]
if (predicate(x)) {
if (nth === 0) return x
nth--
}
index++
}
}
}
```
Tests
```javascript
import { findNth } from './findNth.js'
const list = [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }]
test('happy', () => {
const fn = x => x.a > 1
expect(findNth(fn,1)(list)).toEqual({ a: 3 })
})
test('nothing is found', () => {
const fn = x => x.a > 4
expect(findNth(fn,1)(list)).toBeUndefined()
})
```
[](#findNth)
### flatMap
```typescript
flatMap(transformFn: (x: T extends any[] ? T[number]: never) => U): (listOfLists: T[]) => U[]
```
It maps `fn` over `list` and then flatten the result by one-level.
```javascript
const duplicate = n => [ n, n ]
const list = [ 1, 2, 3 ]
const result = R.flatMap(duplicate)(list)
// => [ 1, 1, 2, 2, 3, 3 ]
```
Try this R.flatMap example in Rambda REPL
All TypeScript definitions
```typescript
flatMap(transformFn: (x: T extends any[] ? T[number]: never) => U): (listOfLists: T[]) => U[];
```
R.flatMap source
```javascript
export function flatMap(fn) {
return list => [].concat(...list.map(fn))
}
```
Tests
```javascript
import { flatMap } from './flatMap.js'
const duplicate = n => [n, n]
test('happy', () => {
const fn = x => [x * 2]
const list = [1, 2, 3]
const result = flatMap(fn)(list)
expect(result).toEqual([2, 4, 6])
})
test('maps then flattens one level', () => {
expect(flatMap(duplicate)([1, 2, 3])).toEqual([1, 1, 2, 2, 3, 3])
})
test('maps then flattens one level', () => {
expect(flatMap(duplicate)([1, 2, 3])).toEqual([1, 1, 2, 2, 3, 3])
})
test('flattens only one level', () => {
const nest = n => [[n]]
expect(flatMap(nest)([1, 2, 3])).toEqual([[1], [2], [3]])
})
test('can compose', () => {
function dec(x) {
return [x - 1]
}
function times2(x) {
return [x * 2]
}
const mdouble = flatMap(times2)
const mdec = flatMap(dec)
expect(mdec(mdouble([10, 20, 30]))).toEqual([19, 39, 59])
})
```
TypeScript test
```typescript
import { flatMap, pipe } from 'rambda'
describe('R.flatMap', () => {
it('happy', () => {
const listOfLists: string[][] = [
['f', 'bar'],
['baz', 'b'],
]
const result = pipe(
listOfLists,
x => x,
flatMap(x => {
x // $ExpectType string
return Number(x) + 1
}),
)
result // $ExpectType number[]
})
})
```
[](#flatMap)
### flatten
```typescript
flatten(list: any[]): T[]
```
It deeply flattens an array.
You must pass expected output type as a type argument.
```javascript
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
```typescript
flatten(list: any[]): T[];
```
R.flatten source
```javascript
import { isArray } from './_internals/isArray.js'
export function flatten(list, input) {
const willReturn = input === undefined ? [] : input
for (let i = 0; i < list.length; i++) {
if (isArray(list[i])) {
flatten(list[i], willReturn)
} else {
willReturn.push(list[i])
}
}
return willReturn
}
```
Tests
```javascript
import { flatten } from './flatten.js'
test('happy', () => {
expect(flatten([1, 2, 3, [[[[[4]]]]]])).toEqual([1, 2, 3, 4])
expect(flatten([1, [2, [[3]]], [4]])).toEqual([1, 2, 3, 4])
expect(flatten([1, [2, [[[3]]]], [4]])).toEqual([1, 2, 3, 4])
expect(flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]])).toEqual([
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
])
})
test('readme example', () => {
const result = flatten([1, 2, [3, 30, [300]], [4]])
expect(result).toEqual([1, 2, 3, 30, 300, 4])
})
```
TypeScript test
```typescript
import { flatten, pipe } from 'rambda'
describe('flatten', () => {
it('happy', () => {
const result = pipe([1, 2, [3, [4]]], flatten)
result // $ExpectType number[]
})
})
```
[](#flatten)
### groupBy
It splits `list` according to a provided `groupFn` function and returns an object.
```javascript
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
[](#groupBy)
### head
```typescript
head(listOrString: T): T extends string ? string :
T extends [] ? undefined:
T extends readonly [infer F, ...infer R] ? F :
T extends readonly [infer F] ? F :
T extends [infer F] ? F :
T extends [infer F, ...infer R] ? F :
T extends unknown[] ? T[number] :
undefined
```
It returns the first element of list or string `input`. It returns `undefined` if array has length of 0.
```javascript
const result = [
R.head([1, 2, 3]),
R.head('foo')
]
// => [1, 'f']
```
Try this R.head example in Rambda REPL
All TypeScript definitions
```typescript
head(listOrString: T): T extends string ? string :
T extends [] ? undefined:
T extends readonly [infer F, ...infer R] ? F :
T extends readonly [infer F] ? F :
T extends [infer F] ? F :
T extends [infer F, ...infer R] ? F :
T extends unknown[] ? T[number] :
undefined;
```
R.head source
```javascript
export function head(listOrString) {
if (typeof listOrString === 'string') {
return listOrString[0] || ''
}
return listOrString[0]
}
```
Tests
```javascript
import { head } from './head.js'
test('head', () => {
expect(head(['fi', 'fo', 'fum'])).toBe('fi')
expect(head([])).toBeUndefined()
expect(head('foo')).toBe('f')
expect(head('')).toBe('')
})
```
TypeScript test
```typescript
import { head, last } from 'rambda'
export const mixedList = [1, 'foo', 3, 'bar']
export const mixedListConst = [1, 'foo', 3, 'bar'] as const
export const numberList = [1, 2, 3]
export const numberListConst = [1, 2, 3] as const
export const emptyList = []
export const emptyString = ''
export const string = 'foo'
describe('R.head', () => {
it('string', () => {
head(string) // $ExpectType string
last(string) // $ExpectType string
})
it('empty string', () => {
head(emptyString) // $ExpectType string
last(emptyString) // $ExpectType string
})
it('array', () => {
head(numberList) // $ExpectType number
head(numberListConst) // $ExpectType 1
last(numberList) // $ExpectType number
last(numberListConst) // $ExpectType 3
})
it('empty array', () => {
const list = [] as const
head(emptyList) // $ExpectType never
head(list) // $ExpectType undefined
last(emptyList) // $ExpectType never
last(list) // $ExpectType undefined
})
it('mixed', () => {
head(mixedList) // $ExpectType string | number
head(mixedListConst) // $ExpectType 1
last(mixedList) // $ExpectType string | number
last(mixedListConst) // $ExpectType "bar"
})
})
```
[](#head)
### includes
```typescript
includes(valueToFind: T): (input: string) => boolean
```
If `input` is string, then this method work as native `String.includes`.
If `input` is array, then `R.equals` is used to define if `valueToFind` belongs to the list.
```javascript
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
```typescript
includes(valueToFind: T): (input: string) => boolean;
includes(valueToFind: T): (input: T[]) => boolean;
```
R.includes source
```javascript
import { isArray } from './_internals/isArray.js'
import { _indexOf } from './equals.js'
export function includes(valueToFind) {
return iterable => {
if (typeof iterable === 'string') {
return iterable.includes(valueToFind)
}
if (!iterable) {
throw new TypeError(`Cannot read property \'indexOf\' of ${iterable}`)
}
if (!isArray(iterable)) {
return false
}
return _indexOf(valueToFind, iterable) > -1
}
}
```
Tests
```javascript
import { includes } from './includes.js'
test('with string as iterable', () => {
const str = 'foo bar'
expect(includes('bar')(str)).toBeTruthy()
expect(includes('never')(str)).toBeFalsy()
})
test('with array as iterable', () => {
const arr = [1, 2, 3]
expect(includes(2)(arr)).toBeTruthy()
expect(includes(4)(arr)).toBeFalsy()
})
test('with list of objects as iterable', () => {
const arr = [{ a: 1 }, { b: 2 }, { c: 3 }]
expect(includes({ c: 3 })(arr)).toBeTruthy()
})
test('with NaN', () => {
const result = includes(Number.NaN)([Number.NaN])
expect(result).toBeTruthy()
})
test('with wrong input that does not throw', () => {
const result = includes(1)(/foo/g)
expect(result).toBeFalsy()
})
```
TypeScript test
```typescript
import { includes, pipe } from 'rambda'
describe('R.includes', () => {
it('happy', () => {
const list = [{ a: { b: '1' } }, { a: { b: '2' } }, { a: { b: '3' } }]
const result = pipe(list, includes({ a: { b: '1' } }))
result // $ExpectType boolean
})
it('with string', () => {
const result = pipe('foo', includes('bar'))
result // $ExpectType boolean
})
})
```
[](#includes)
### indexOf
It uses `R.equals` for list of objects/arrays or native `indexOf` for any other case.
```javascript
const result = [
R.indexOf({a:1})([{a:1}, {a:2}]),
R.indexOf(2)([1, 2, 3]),
]
// => [0, 1]
```
Try this R.indexOf example in Rambda REPL
[](#indexOf)
### init
```typescript
init(input: T): T extends readonly [...infer U, any] ? U : [...T]
```
It returns all but the last element of list or string `input`.
```javascript
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
```typescript
init(input: T): T extends readonly [...infer U, any] ? U : [...T];
init(input: string): string;
```
R.init source
```javascript
import { baseSlice } from './_internals/baseSlice.js'
export function init(input) {
if (typeof input === 'string') {
return input.slice(0, -1)
}
return input.length ? baseSlice(input, 0, -1) : []
}
```
Tests
```javascript
import { init } from './init.js'
test('with array', () => {
expect(init([1, 2, 3])).toEqual([1, 2])
expect(init([1, 2])).toEqual([1])
expect(init([1])).toEqual([])
expect(init([])).toEqual([])
expect(init([])).toEqual([])
expect(init([1])).toEqual([])
})
test('with string', () => {
expect(init('foo')).toBe('fo')
expect(init('f')).toBe('')
expect(init('')).toBe('')
})
```
TypeScript test
```typescript
import { init } from 'rambda'
describe('R.init', () => {
it('with string', () => {
const result = init('foo')
result // $ExpectType string
})
it('with list - one type', () => {
const result = init([1, 2, 3])
result // $ExpectType number[]
})
it('with list - mixed types', () => {
const result = init([1, 2, 3, 'foo', 'bar'])
result // $ExpectType (string | number)[]
})
})
```
[](#init)
### innerJoin
It returns a new list by applying a `predicate` function to all elements of `list1` and `list2` and keeping only these elements where `predicate` returns `true`.
```javascript
const list1 = [1, 2, 3, 4, 5]
const list2 = [4, 5, 6]
const predicate = (x, y) => x >= y
const result = R.innerJoin(predicate, list1)(list2)
// => [4, 5]
```
Try this R.innerJoin example in Rambda REPL
[](#innerJoin)
### interpolate
```typescript
interpolate(inputWithTags: string): (templateArguments: object) => string
```
It generates a new string from `inputWithTags` by replacing all `{{x}}` occurrences with values provided by `templateArguments`.
```javascript
const inputWithTags = 'foo is {{bar}} even {{a}} more'
const templateArguments = {"bar":"BAR", a: 1}
const result = R.interpolate(inputWithTags, templateArguments)
const expected = 'foo is BAR even 1 more'
// => `result` is equal to `expected`
```
Try this R.interpolate example in Rambda REPL
All TypeScript definitions
```typescript
interpolate(inputWithTags: string): (templateArguments: object) => string;
// API_MARKER_END
// ============================================
export as namespace R
```
R.interpolate source
```javascript
const getOccurrences = input => input.match(/{{\s*.+?\s*}}/g)
const getOccurrenceProp = occurrence => occurrence.replace(/{{\s*|\s*}}/g, '')
const replace = ({ inputHolder, prop, replacer }) => {
const regexBase = `{{${prop}}}`
const regex = new RegExp(regexBase, 'g')
return inputHolder.replace(regex, replacer)
}
export function interpolate(input) {
return templateInput => {
const occurrences = getOccurrences(input)
if (occurrences === null) {
return input
}
let inputHolder = input
for (const occurrence of occurrences) {
const prop = getOccurrenceProp(occurrence)
inputHolder = replace({
inputHolder,
prop,
replacer: templateInput[prop],
})
}
return inputHolder
}
}
```
Tests
```javascript
import { interpolate } from './interpolate.js'
import { pipe } from './pipe.js'
test('happy', () => {
const result = pipe(
{ name: 'John', age: 30 },
interpolate('My name is {{name}} and I am {{age}} years old')
)
expect(result).toBe('My name is John and I am 30 years old')
})
```
TypeScript test
```typescript
import { interpolate } from 'rambda'
const templateInput = 'foo {{x}} baz'
const templateArguments = { x: 'led zeppelin' }
it('R.interpolate', () => {
const result = interpolate(templateInput)(templateArguments)
result // $ExpectType string
})
```
[](#interpolate)
### intersection
It loops through `listA` and `listB` and returns the intersection of the two according to `R.equals`.
> :boom: There is slight difference between Rambda and Ramda implementation. Ramda.intersection(['a', 'b', 'c'], ['c', 'b']) result is "[ 'c', 'b' ]", but Rambda result is "[ 'b', 'c' ]".
```javascript
const listA = [ { id : 1 }, { id : 2 }, { id : 3 }, { id : 4 } ]
const listB = [ { id : 3 }, { id : 4 }, { id : 5 }, { id : 6 } ]
const result = R.intersection(listA)(listB)
// => [{ id : 3 }, { id : 4 }]
```
Try this R.intersection example in Rambda REPL
[](#intersection)
### intersperse
It adds a `separator` between members of `list`.
```javascript
const list = [ 0, 1, 2, 3 ]
const separator = 10
const result = R.intersperse(separator)(list)
// => [0, 10, 1, 10, 2, 10, 3]
```
Try this R.intersperse example in Rambda REPL
[](#intersperse)
### join
```typescript
join(glue: string): (list: T[]) => string
```
It returns a string of all `list` instances joined with a `glue`.
```javascript
R.join('-', [1, 2, 3]) // => '1-2-3'
```
Try this R.join example in Rambda REPL
All TypeScript definitions
```typescript
join(glue: string): (list: T[]) => string;
```
R.join source
```javascript
export function join(glue) {
return list => list.join(glue)
}
```
TypeScript test
```typescript
import { join, pipe } from 'rambda'
it('R.join', () => {
const result = pipe([1, 2, 3], join('|'))
result // $ExpectType string
})
```
[](#join)
### last
```typescript
last(listOrString: T): T extends string ? string :
T extends [] ? undefined :
T extends readonly [...infer R, infer L] ? L :
T extends readonly [infer L] ? L :
T extends [infer L] ? L :
T extends [...infer R, infer L] ? L :
T extends unknown[] ? T[number] :
undefined
```
It returns the last element of `input`, as the `input` can be either a string or an array. It returns `undefined` if array has length of 0.
```javascript
const result = [
R.last([1, 2, 3]),
R.last('foo'),
]
// => [3, 'o']
```
Try this R.last example in Rambda REPL
All TypeScript definitions
```typescript
last(listOrString: T): T extends string ? string :
T extends [] ? undefined :
T extends readonly [...infer R, infer L] ? L :
T extends readonly [infer L] ? L :
T extends [infer L] ? L :
T extends [...infer R, infer L] ? L :
T extends unknown[] ? T[number] :
undefined;
```
R.last source
```javascript
export function last(listOrString) {
if (typeof listOrString === 'string') {
return listOrString[listOrString.length - 1] || ''
}
return listOrString[listOrString.length - 1]
}
```
Tests
```javascript
import { last } from './last.js'
test('with list', () => {
expect(last([1, 2, 3])).toBe(3)
expect(last([])).toBeUndefined()
})
test('with string', () => {
expect(last('abc')).toBe('c')
expect(last('')).toBe('')
})
```
[](#last)
### lastIndexOf
```typescript
lastIndexOf(target: T): (list: T[]) => number
```
It returns the last index of `target` in `list` array.
`R.equals` is used to determine equality between `target` and members of `list`.
If there is no such index, then `-1` is returned.
```javascript
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
```typescript
lastIndexOf(target: T): (list: T[]) => number;
```
R.lastIndexOf source
```javascript
import { _lastIndexOf } from './equals.js'
export function lastIndexOf(valueToFind) {
return list => _lastIndexOf(valueToFind, list)
}
```
Tests
```javascript
import { lastIndexOf } from './lastIndexOf.js'
test('with NaN', () => {
expect(lastIndexOf(Number.NaN)([Number.NaN])).toBe(0)
})
test('will throw with bad input', () => {
expect(() => indexOf([])(true)).toThrowError('indexOf is not defined')
})
test('without list of objects - no R.equals', () => {
expect(lastIndexOf(3)([1, 2, 3, 4])).toBe(2)
expect(lastIndexOf(10)([1, 2, 3, 4])).toBe(-1)
})
test('list of objects uses R.equals', () => {
const listOfObjects = [{ a: 1 }, { b: 2 }, { c: 3 }]
expect(lastIndexOf({ c: 4 })(listOfObjects)).toBe(-1)
expect(lastIndexOf({ c: 3 })(listOfObjects)).toBe(2)
})
test('list of arrays uses R.equals', () => {
const listOfLists = [[1], [2, 3], [2, 3, 4], [2, 3], [1], []]
expect(lastIndexOf([])(listOfLists)).toBe(5)
expect(lastIndexOf([1])(listOfLists)).toBe(4)
expect(lastIndexOf([2, 3, 4])(listOfLists)).toBe(2)
expect(lastIndexOf([2, 3, 5])(listOfLists)).toBe(-1)
})
```
TypeScript test
```typescript
import { lastIndexOf, pipe } from 'rambda'
describe('R.lastIndexOf', () => {
const result = pipe([{ a: 1 }, { a: 2 }, { a: 3 }], lastIndexOf({ a: 2 }))
result // $ExpectType number
})
```
[](#lastIndexOf)
### map
```typescript
map(
fn: (value: T[number], index: number) => U,
): (data: T) => Mapped
```
It returns the result of looping through `iterable` with `fn`.
It works with both array and object.
```javascript
const fn = x => x * 2
const iterable = [1, 2]
const obj = {a: 1, b: 2}
const result = R.map(fn)(iterable),
// => [2, 4]
```
Try this R.map example in Rambda REPL
All TypeScript definitions
```typescript
map(
fn: (value: T[number], index: number) => U,
): (data: T) => Mapped;
map(
fn: (value: T[number]) => U,
): (data: T) => Mapped;
map(
fn: (value: T[number], index: number) => U,
data: T
) : Mapped;
map(
fn: (value: T[number]) => U,
data: T
) : Mapped;
```
R.map source
```javascript
export function map(fn) {
return list => {
let index = 0
const willReturn = Array(list.length)
while (index < list.length) {
willReturn[