UNPKG

1.96 kBJavaScriptView Raw
1
2
3
4!function(exports) {
5 var pointerCache = {}
6 , hasOwn = pointerCache.hasOwnProperty
7
8 exports.clone = clone
9 exports.mergePatch = mergePatch
10 exports.isObject = isObject
11
12 /**
13 * JSON Merge Patch
14 * @see https://tools.ietf.org/html/rfc7396
15 */
16
17 function mergePatch(target, patch, changed, previous, pointer) {
18 var undef, key, oldVal, val, len, nextPointer
19 if (isObject(patch)) {
20 if (!pointer) {
21 pointer = ""
22 }
23 if (!isObject(target)) {
24 target = {}
25 }
26 for (key in patch) if (
27 undef !== (oldVal = target[key], val = patch[key]) &&
28 hasOwn.call(patch, key) &&
29 (
30 undef == val ?
31 undef !== oldVal && delete target[key] :
32 target[key] !== val
33 )
34 ) {
35 nextPointer = pointer + "/" + key.replace(/~/g, "~0").replace(/\//g, "~1")
36 len = changed && isObject(target[key]) && changed.length
37 if (undef != val) {
38 target[key] = mergePatch(target[key], val, changed, previous, nextPointer)
39 }
40 if (len === false || changed && len != changed.length) {
41 changed.push(nextPointer)
42 if (previous && !isObject(oldVal)) {
43 previous[nextPointer] = oldVal
44 }
45 }
46 }
47 } else {
48 if (changed && isObject(target)) {
49 val = {}
50 for (key in target) if (hasOwn.call(target, key)) {
51 val[key] = null
52 }
53 mergePatch(target, val, changed, previous, pointer)
54 }
55 target = patch
56 }
57 return target
58 }
59
60 function clone(obj) {
61 var temp, key
62 if (obj && typeof obj == "object") {
63 // new Date().constructor() returns a string
64 temp = obj instanceof Date ? new Date(+obj) :
65 obj instanceof RegExp ? RegExp(obj.source, (""+obj).split("/").pop()) :
66 obj.constructor()
67 for (key in obj) if (hasOwn.call(obj, key)) {
68 temp[key] = clone(obj[key])
69 }
70 obj = temp
71 }
72 return obj
73 }
74
75 function isObject(obj) {
76 return !!obj && obj.constructor === Object
77 }
78
79// `this` refers to the `window` in browser and to the `exports` in Node.js.
80}(this.JSON || this)
81
82