Last active
September 28, 2021 10:08
-
-
Save rawnly/ed679777fd912cfb1a2d417b5461ebca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example Usage: