]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/core-utils/common/object.ts
9780b2594327af1b0113dd1e6ae574300e74d7da
[github/Chocobozzz/PeerTube.git] / shared / core-utils / common / object.ts
1 function pick <O extends object, K extends keyof O> (object: O, keys: K[]): Pick<O, K> {
2 const result: any = {}
3
4 for (const key of keys) {
5 if (Object.prototype.hasOwnProperty.call(object, key)) {
6 result[key] = object[key]
7 }
8 }
9
10 return result
11 }
12
13 function omit <O extends object, K extends keyof O> (object: O, keys: K[]): Exclude<O, K> {
14 const result: any = {}
15 const keysSet = new Set(keys) as Set<string>
16
17 for (const [ key, value ] of Object.entries(object)) {
18 if (keysSet.has(key)) continue
19
20 result[key] = value
21 }
22
23 return result
24 }
25
26 function getKeys <O extends object, K extends keyof O> (object: O, keys: K[]): K[] {
27 return (Object.keys(object) as K[]).filter(k => keys.includes(k))
28 }
29
30 function sortObjectComparator (key: string, order: 'asc' | 'desc') {
31 return (a: any, b: any) => {
32 if (a[key] < b[key]) {
33 return order === 'asc' ? -1 : 1
34 }
35
36 if (a[key] > b[key]) {
37 return order === 'asc' ? 1 : -1
38 }
39
40 return 0
41 }
42 }
43
44 function shallowCopy <T> (o: T): T {
45 return Object.assign(Object.create(Object.getPrototypeOf(o)), o)
46 }
47
48 function simpleObjectsDeepEqual (a: any, b: any) {
49 if (a === b) return true
50
51 if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) {
52 return false
53 }
54
55 const keysA = Object.keys(a)
56 const keysB = Object.keys(b)
57
58 if (keysA.length !== keysB.length) return false
59
60 for (const key of keysA) {
61 if (!keysB.includes(key)) return false
62
63 if (!simpleObjectsDeepEqual(a[key], b[key])) return false
64 }
65
66 return true
67 }
68
69 export {
70 pick,
71 omit,
72 getKeys,
73 shallowCopy,
74 sortObjectComparator,
75 simpleObjectsDeepEqual
76 }