Skip to content

Instantly share code, notes, and snippets.

@tompng
Created July 17, 2019 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tompng/9a6edefc73e21ad693b4ead87437859c to your computer and use it in GitHub Desktop.
Save tompng/9a6edefc73e21ad693b4ead87437859c to your computer and use it in GitHub Desktop.
function serializeDOM(dom){
return {
tag: dom.tagName,
class: dom.className,
children: [...dom.childNodes].map(a=>serializeDOM(a))
}
}
diffs = []
function diff(oa, ob, path, ac) {
if (JSON.stringify(oa) === JSON.stringify(ob)) return null
const keys = Object.keys({...oa, ...ob})
for (const k of keys) {
const a = oa[k], b = ob[k]
if (JSON.stringify(a) == JSON.stringify(b)) continue
const aa = Array.isArray(a)
const ab = Array.isArray(b)
if (typeof a !== typeof b || typeof a !== 'object' || (!a !== !b) || aa !== ab || a.length !== b.length) {
ac[k] = { a, b, path }
diffs.push(ac[k])
continue
}
if (aa) {
ac[k] = []
for (let i = 0; i < a.length; i++) {
ac[k].push(diff(a[i], b[i], [...path, k, i], {}))
}
} else {
ac[k] = {}
diff(a, b, [...path, k], ac[k])
}
}
return ac
}
// do something
data1 = serializeDOM(document.body)
// do something else
data2 = serializeDOM(document.body)
diffs = []; diff(data1, data2, [], {})
diffs.map(x=>[x.path.filter(a=>a>=0), { a: x.a, b: x.b }])
// [0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 2], a: "DIV", b: undefined
// [0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 2], a: "memo-selected", b: undefined
// [0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 1, 0, 1, 0, 2], a: undefined, b: "DIV"
// [0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 1, 0, 1, 0, 2], a: undefined, b: "memo-selected"
// [0, 0, 0, 0, 1, 0, 0, 0, 12, 5, 9, 1, 1, 2], a: "item active", b: "item"
// [0, 0, 0, 0, 1, 0, 0, 0, 12, 5, 9, 1, 1, 3], a: "item", b: "item active"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment