v
and v1
equate to the two virtual dom trees we're comparing.var v_hashes = v.children.map(c => c.hashcode )
var v1_hashes = v1.children.map(c => c.hashcode )
v1
hashes and whether they exist in the v
hashes using indexOf()
.v
hash array [1111, 2222]
and the v1
hash array [3333, 1111, 2222]
we'll get [-1, 0, 1]
.indexOf()
is telling us: the zeroth item in v1
doesn't exist in v
but the first is the zeroth element, and the second is the first element.v1
's hash in the returning array for later reference.var positions = v1_hashes.map((h, i) => v_hashes.indexOf(h) )
v1
virtual dom that's not in the v
virtual dom, i.e. we find a -1 value.positions.forEach((index_in_v, v1_pos) => {
if(index_in_v != -1) return
console.log("insert " + v1_hashes[v1_pos] + " into " + v1_pos + " at " + path)
v.children.splice(v1_pos, 0, JSON.parse(JSON.stringify(v1.children[v1_pos])))
})
v
array. This means, later, when we compare the two tree branches our compare function will see they're the same.console.log
-- that the DOM manipulation function must actually do this rearragement of the DOM.v
virtual DOM tree was:[{
"type": "node",
"name": "DIV",
"attrs": [],
"children": [{
"type": "node",
"name": "P",
"attrs": [],
"children": [{
"type": "text",
"value": "original",
"children": [],
"hashcode": -68148979
}],
"hashcode": -1072170396
}],
"hashcode": -154850033
}]
v1
was:[{
"type": "node",
"name": "DIV",
"attrs": [],
"children": [{
"type": "node",
"name": "P",
"attrs": [],
"children": [{
"type": "text",
"value": "new",
"children": [],
"hashcode": 1156737192
}],
"hashcode": -1348153726
}, {
"type": "node",
"name": "P",
"attrs": [],
"children": [{
"type": "text",
"value": "original",
"children": [],
"hashcode": -68148979
}],
"hashcode": -1072170396
}],
"hashcode": 1511584547
}]
v1
had a new P
node (hashcode: -1348153726) above the old one.compare = function(v, v1, path) {
var v_hashes = v.children.map(c => c.hashcode )
var v1_hashes = v1.children.map(c => c.hashcode )
var positions = v1_hashes.map((h, i) => v_hashes.indexOf(h) )
positions.forEach((index_in_v, v1_pos) => {
if(index_in_v != -1) return
console.log("insert " + v1_hashes[v1_pos] + " into " + v1_pos + " at " + path)
v.children.splice(v1_pos, 0, JSON.parse(JSON.stringify(v1.children[v1_pos])))
})
v.children.forEach((_, i) => compare(v.children[i], v1.children[i], path + "" + i) )
};
compare(JSON.parse(JSON.stringify(vd[0])), JSON.parse(JSON.stringify(vd1[0])), "")
insert -1348153726 into 0
Edit on Github!