aboutsummaryrefslogtreecommitdiffhomepage
path: root/shared/core-utils/common/object.ts
blob: 49d209819a9793d190205849877289a311b64e85 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function pick <O extends object, K extends keyof O> (object: O, keys: K[]): Pick<O, K> {
  const result: any = {}

  for (const key of keys) {
    if (Object.prototype.hasOwnProperty.call(object, key)) {
      result[key] = object[key]
    }
  }

  return result
}

function getKeys <O extends object, K extends keyof O> (object: O, keys: K[]): K[] {
  return (Object.keys(object) as K[]).filter(k => keys.includes(k))
}

function sortObjectComparator (key: string, order: 'asc' | 'desc') {
  return (a: any, b: any) => {
    if (a[key] < b[key]) {
      return order === 'asc' ? -1 : 1
    }

    if (a[key] > b[key]) {
      return order === 'asc' ? 1 : -1
    }

    return 0
  }
}

export {
  pick,
  getKeys,
  sortObjectComparator
}