-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
40 lines (36 loc) · 1.04 KB
/
index.js
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
/**
* Test if a value is a plain object.
* @param {*} val - A value.
* @return {boolean} true if `val` is a plain object.
*/
const isObject = val =>
val != null && typeof val === 'object' && Array.isArray(val) === false;
/**
* Apply a JSON merge patch. The origin is *not* modified, but unchanged
* properties will be recycled.
*
* @param {*} origin - The value to patch.
* @param {*} patch - An [RFC 7396](https://tools.ietf.org/html/rfc7396) patch.
* @return {*} The patched value.
*/
export function apply(origin, patch) {
if (!isObject(patch)) {
// If the patch is not an object, it replaces the origin.
return patch;
}
const result = !isObject(origin)
? // Non objects are being replaced.
{}
: // Make sure we never modify the origin.
Object.assign({}, origin);
Object.keys(patch).forEach(key => {
const patchVal = patch[key];
if (patchVal === null) {
delete result[key];
} else {
result[key] = apply(result[key], patchVal);
}
});
return result;
}
export default apply;