Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import lift from 'space-lift'
- import 'space-lift/commonjs/all'
- type Item = {
- id: number
- value: string
- }
- const items: Item[] = [
- { id: 1, value: 'one' },
- { id: 2, value: 'two' },
- ]
- // update multiple items inside an array
- function updateMultipleItems(items: Item[], newValues: Item[]): Item[] {
- return items.map(item =>
- lift(newValues)
- .find(({ id }) => id === item.id)
- .map(({ value }) => ({ id: item.id, value }))
- .getOrElse(item)
- )
- }
- const updatedItems = updateMultipleItems(items, [
- { id: 1, value: 'ok' },
- { id: 2, value: 'good' },
- ])
- // sort an array
- type SortOption<T> = {
- by: (item: T) => string | number
- reverse?: boolean
- }
- function sortBy<T>(arr: T[], opts: SortOption<T>[]): T[] {
- return arr.sort((a, b) => {
- for (let index = 0; index < opts.length; index++) {
- const { by, reverse = false } = opts[index]
- if (by(a) < by(b)) return reverse ? 1 : -1
- if (by(a) > by(b)) return reverse ? -1 : 1
- }
- return 0
- })
- }
Add Comment
Please, Sign In to add comment