Last active
December 20, 2017 03:20
-
-
Save derpycoder/1fdc5cb676f0806781ec754da0a31a46 to your computer and use it in GitHub Desktop.
Apply changes from one object to another if they differ.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Configs | |
var origConfig = { | |
p: { | |
a: 23, | |
b: 92, | |
c: { | |
num: 1 | |
} | |
}, | |
q: { | |
x: 32, | |
y: 29 | |
} | |
}; | |
var diffConfig = { | |
p: { | |
c: { | |
num: 3 | |
} | |
}, | |
q: { | |
x: 99 | |
}, | |
z: 23 // Unnecessary | |
}; | |
// Holy Grail (Breadth First Traversal): Solution to our Problems! | |
function modifyWhatDiffers(original, diff) { | |
var stack = []; | |
if (!original || !diff) { | |
return original; | |
} | |
stack.push({ | |
o: original, | |
d: diff | |
}); | |
// Runs only for modifications in the diff object | |
while (stack.length > 0) { | |
let obj = stack.shift(); | |
for (var key in obj.d) { | |
if (obj.o.hasOwnProperty(key) && obj.d.hasOwnProperty(key)) { | |
if (typeof obj.o[key] === "object") { | |
stack.push({ | |
o: obj.o[key], | |
d: obj.d[key] | |
}); | |
} else if (obj.o[key] !== obj.d[key]) { | |
obj.o[key] = obj.d[key]; | |
} | |
} | |
} | |
} | |
return original; | |
} | |
// Pass in a Deep Copy of the Original, use any method you want! | |
let patchedConfig = modifyWhatDiffers( | |
JSON.parse(JSON.stringify(origConfig)), | |
diffConfig | |
); | |
console.log(JSON.stringify(origConfig)); | |
console.log(JSON.stringify(diffConfig)); | |
console.log(JSON.stringify(patchedConfig)); | |
// {"p":{"a":23,"b":92,"c":{"num":1}},"q":{"x":32,"y":29}} | |
// {"p":{"c":{"num":3}},"q":{"x":99}},"z":23} | |
// {"p":{"a":23,"b":92,"c":{"num":3}},"q":{"x":99,"y":29}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment