R's match in TypeScript

Rosetta Stone: tcl/match

How to use

Install via yarn add locutus and import: import { match } from 'locutus/r/base/match'.

Or with CommonJS: const { match } = require('locutus/r/base/match')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1match('b', ['a', 'b', 'c'])2
2match('z', ['a', 'b', 'c'])null
3match(3, [1, 2, 3, 2], 0)3

Notes

  • Returns the first 1-based match position, similar to R match.

  • Returns nomatch when provided, otherwise null.

Here's what our current TypeScript equivalent to R's match looks like.

export function match(
value: string | number | boolean | null,
table: Array<string | number | boolean | null> | unknown,
nomatch: number | null = null,
): number | null {
// discuss at: https://locutus.io/r/match/
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Returns the first 1-based match position, similar to R match.
// note 2: Returns nomatch when provided, otherwise null.
// example 1: match('b', ['a', 'b', 'c'])
// returns 1: 2
// example 2: match('z', ['a', 'b', 'c'])
// returns 2: null
// example 3: match(3, [1, 2, 3, 2], 0)
// returns 3: 3

if (!Array.isArray(table)) {
return nomatch
}

for (let i = 0; i < table.length; i++) {
if (Object.is(table[i], value)) {
return i + 1
}
}

return nomatch
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


We have 12 R functions so far - help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

  • Get inspiration from the R base documentation.
  • Click "New file" in the appropriate folder on GitHub. This will fork the project to your account, directly add the file to it, and send a Pull Request to us.

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.

« More R base functions


Star