Skip to content

Instantly share code, notes, and snippets.

@rawnly
Last active September 28, 2021 10:08
Show Gist options
  • Save rawnly/ed679777fd912cfb1a2d417b5461ebca to your computer and use it in GitHub Desktop.
Save rawnly/ed679777fd912cfb1a2d417b5461ebca to your computer and use it in GitHub Desktop.
import { match, Pattern } from 'ts-pattern'
/**
* Returns an element of the array matching given pattern or `null`
*/
export const find = <T>(data: T[], query: Pattern<T>): T | undefined =>
data
.find(item =>
match(item)
.with(query, () => true)
.otherwise(() => false)
)
/**
* Returns the index of an element in the array
* matching given pattern or `undefined`
*/
export const findIndex = <T>(data: T[], query: Pattern<T>): number =>
data
.findIndex(item =>
match(item)
.with(query, () => true)
.otherwise(() => false)
)
/**
* Updates an array element matching given pattern
*/
export const update = <T>(data: T[], query: Pattern<T>, update: Partial<T>): T[] =>
data
.map( item =>
match(item)
.with(query, () => ({ ...item, ...update }))
.otherwise(() => item)
)
/**
* Removes an array element matching given pattern
*/
export const remove = <T>(data: T[], query: Pattern<T>): T[] =>
data
.filter(
item =>
match(item)
.with(query, () => false)
.otherwise(() => true)
)
@rawnly
Copy link
Author

rawnly commented Sep 28, 2021

Example Usage:

type Person = {
	id: number;
	name: string;
	age: number;
}


let people: Person[] = [{
	id: 1,
	name: 'John Doe',
	age: 30
}, { 
	id: 2,
	name: 'Elisa Doe',
	age: 32
}]

people = update(people, { age: 30 }, { age: 35 })

const person = find(people, { name: 'John Doe' })

console.log(`${person.name} is ${person.age}`) //=> "John Doe is 35"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment