-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapply.ts
More file actions
96 lines (94 loc) · 2.99 KB
/
apply.ts
File metadata and controls
96 lines (94 loc) · 2.99 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { DraftType, Operation, Patches } from './interface';
import { deepClone, get, getType, unescapePath } from './utils';
/**
* Apply patches to the state.
*/
export function apply(state: any, patches: Patches) {
let i;
for (i = patches.length - 1; i >= 0; i -= 1) {
const { value, op, path } = patches[i];
if (
(!path.length && op === Operation.Replace) ||
(path === '' && op === Operation.Add)
) {
state = value;
break;
}
}
if (i > -1) {
patches = patches.slice(i + 1);
}
patches.forEach((patch) => {
const { path: _path, op } = patch;
const path = unescapePath(_path);
let base: any = state;
for (let index = 0; index < path.length - 1; index += 1) {
const parentType = getType(base);
let key = path[index];
if (typeof key !== 'string' && typeof key !== 'number') {
key = String(key);
}
if (
((parentType === DraftType.Object || parentType === DraftType.Array) &&
(key === '__proto__' || key === 'constructor')) ||
(typeof base === 'function' && key === 'prototype')
) {
throw new Error(
`Patching reserved attributes like __proto__ and constructor is not allowed.`
);
}
// use `index` in Set draft
base = get(
getType(base) === DraftType.Set ? Array.from(base) : base,
key
);
if (typeof base !== 'object') {
throw new Error(`Cannot apply patch at '${path.join('/')}'.`);
}
}
const type = getType(base);
// ensure the original patch is not modified.
const value = deepClone(patch.value);
const key = path[path.length - 1];
switch (op) {
case Operation.Replace:
switch (type) {
case DraftType.Map:
return base.set(key, value);
case DraftType.Set:
throw new Error(`Cannot apply replace patch to set.`);
default:
return (base[key] = value);
}
case Operation.Add:
switch (type) {
case DraftType.Array:
// If the "-" character is used to
// index the end of the array (see [RFC6901](https://datatracker.ietf.org/doc/html/rfc6902)),
// this has the effect of appending the value to the array.
return key === '-'
? base.push(value)
: base.splice(key as number, 0, value);
case DraftType.Map:
return base.set(key, value);
case DraftType.Set:
return base.add(value);
default:
return (base[key] = value);
}
case Operation.Remove:
switch (type) {
case DraftType.Array:
return base.splice(key as number, 1);
case DraftType.Map:
return base.delete(key);
case DraftType.Set:
return base.delete(patch.value);
default:
return delete base[key];
}
default:
throw new Error(`Unsupported patch operation: ${op}.`);
}
});
}