-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
54 lines (49 loc) · 1.21 KB
/
mod.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
type Data = Record<string, any>
function escape(path: string): string {
return path.replaceAll('~1', '/').replaceAll('~0', '~')
}
function getPath(pointer: string): string[] {
if (!pointer.startsWith('/')) throw new Error (`Invalid pointer "${pointer}"`)
return pointer.substring(1).split('/').map(escape)
}
function deepApply(data: Data, path: string[], value: any): void {
if (path[0] === '-' && Array.isArray(data)) data.push(value)
if (data[path[0]] === undefined) data[path[0]] = {}
if (path.length === 1) {
data[path[0]] = value
return
}
return deepApply(data[path[0]], path.slice(1), value)
}
/**
* Return the value at the given JSON pointer in object.
*
* @param data object
* @param pointer string
* @return any
*/
export function get(
data: Data,
pointer: string
): any {
let value = data
if (pointer === '') return data
for (const path of getPath(pointer)) {
if (value !== undefined) value = value[path]
}
return value
}
/**
* Update the value at the given JSON pointer in object.
*
* @param data object
* @param pointer string
* @return void
*/
export function set(
data: Data,
pointer: string,
value: any
): void {
deepApply(data, getPath(pointer), value)
}