-
Notifications
You must be signed in to change notification settings - Fork 713
/
Copy pathindex.ts
87 lines (67 loc) · 2.22 KB
/
index.ts
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { isEqual } from 'ohash/utils'
export function pick<Data extends object, Keys extends keyof Data>(data: Data, keys: Keys[]): Pick<Data, Keys> {
const result = {} as Pick<Data, Keys>
for (const key of keys) {
result[key] = data[key]
}
return result
}
export function omit<Data extends object, Keys extends keyof Data>(data: Data, keys: Keys[]): Omit<Data, Keys> {
const result = { ...data }
for (const key of keys) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete result[key]
}
return result as Omit<Data, Keys>
}
export function get(object: Record<string, any> | undefined, path: (string | number)[] | string, defaultValue?: any): any {
if (typeof path === 'string') {
path = path.split('.').map((key) => {
const numKey = Number(key)
return Number.isNaN(numKey) ? key : numKey
})
}
let result: any = object
for (const key of path) {
if (result === undefined || result === null) {
return defaultValue
}
result = result[key]
}
return result !== undefined ? result : defaultValue
}
export function set(object: Record<string, any>, path: (string | number)[] | string, value: any): void {
if (typeof path === 'string') {
path = path.split('.').map((key) => {
const numKey = Number(key)
return Number.isNaN(numKey) ? key : numKey
})
}
path.reduce((acc, key, i) => {
if (acc[key] === undefined) acc[key] = {}
if (i === path.length - 1) acc[key] = value
return acc[key]
}, object)
}
export function looseToNumber(val: any): any {
const n = Number.parseFloat(val)
return Number.isNaN(n) ? val : n
}
export function compare<T>(value?: T, currentValue?: T, comparator?: string | ((a: T, b: T) => boolean)) {
if (value === undefined || currentValue === undefined) {
return false
}
if (typeof value === 'string') {
return value === currentValue
}
if (typeof comparator === 'function') {
return comparator(value, currentValue)
}
if (typeof comparator === 'string') {
return get(value!, comparator) === get(currentValue!, comparator)
}
return isEqual(value, currentValue)
}
export function isArrayOfArray<A>(item: A[] | A[][]): item is A[][] {
return Array.isArray(item[0])
}