Guest User

Untitled

a guest
Dec 14th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. import lift from 'space-lift'
  2. import 'space-lift/commonjs/all'
  3.  
  4. type Item = {
  5. id: number
  6. value: string
  7. }
  8.  
  9. const items: Item[] = [
  10. { id: 1, value: 'one' },
  11. { id: 2, value: 'two' },
  12. ]
  13.  
  14. // update multiple items inside an array
  15. function updateMultipleItems(items: Item[], newValues: Item[]): Item[] {
  16. return items.map(item =>
  17. lift(newValues)
  18. .find(({ id }) => id === item.id)
  19. .map(({ value }) => ({ id: item.id, value }))
  20. .getOrElse(item)
  21. )
  22. }
  23.  
  24. const updatedItems = updateMultipleItems(items, [
  25. { id: 1, value: 'ok' },
  26. { id: 2, value: 'good' },
  27. ])
  28.  
  29. // sort an array
  30. type SortOption<T> = {
  31. by: (item: T) => string | number
  32. reverse?: boolean
  33. }
  34.  
  35. function sortBy<T>(arr: T[], opts: SortOption<T>[]): T[] {
  36. return arr.sort((a, b) => {
  37. for (let index = 0; index < opts.length; index++) {
  38. const { by, reverse = false } = opts[index]
  39.  
  40. if (by(a) < by(b)) return reverse ? 1 : -1
  41. if (by(a) > by(b)) return reverse ? -1 : 1
  42. }
  43.  
  44. return 0
  45. })
  46. }
Add Comment
Please, Sign In to add comment