forked from utags/userscripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobj.ts
More file actions
63 lines (53 loc) · 1.65 KB
/
Copy pathobj.ts
File metadata and controls
63 lines (53 loc) · 1.65 KB
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
export function deepMergeReplaceArrays(target: any, source: any): any {
if (target === null || typeof target !== 'object') return source
if (source === null || typeof source !== 'object') return source ?? target
// Arrays: replace with source
if (Array.isArray(target) && Array.isArray(source)) return source
const out: Record<string, any> = { ...target }
const src = source as Record<string, any>
const trg = target as Record<string, any>
for (const k of Object.keys(src)) {
const sv = src[k]
const tv = trg[k]
if (Array.isArray(sv)) out[k] = sv
else if (sv && typeof sv === 'object')
out[k] = deepMergeReplaceArrays(tv ?? {}, sv)
else out[k] = sv
}
return out
}
export const normalizeToDefaultType = (val: any, dv: any): any => {
const t = typeof dv
if (t === 'number') {
const n = Number(val)
return Number.isFinite(n) ? n : dv
}
if (t === 'object') {
return val && typeof val === 'object' ? val : dv
}
return typeof val === t ? val : dv
}
export function setOrDelete(
obj: Record<string, any>,
key: string,
value: any,
defaultValue: any
): void {
const normalized = normalizeToDefaultType(value, defaultValue)
const isEqual = (a: any, b: any): boolean => {
// Primitive compare; fallback to JSON for objects
if (a === b) return true
if (a && b && typeof a === 'object' && typeof b === 'object') {
try {
return JSON.stringify(a) === JSON.stringify(b)
} catch {}
}
return false
}
if (isEqual(normalized, defaultValue)) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete obj[key]
} else {
obj[key] = normalized
}
}