I was asked this as an interview question. I was also asked to assume that there is a function which can compare and say two nodes are identical. I would like to implement that function as well. I'm not sure what's a sure shot way of saying that in pure JavaScript.
O O / \ / \ O O O O /|\ /|\ O O O O O O
Assume two DOM trees with roots:
rootA
androotB
, therootB
tree being a clone of therootA
tree. Write a function which takes a node inrootA
and finds a clone node in the other tree.
I believe there is a better solution than recursion.
function walkTheDom(root, cb) {
if (!root) {
return;
}
var r = root;
if (cb (r)) {
foundNode = r;
return;
}
r = r.firstChild;
while (r) {
walkTheDom(r, cb);
r = r.nextSibling;
}
}
var compare = function (el) {
//return true if nodes are equal
//false if they're not
}
function findNode(node, rootB) {
var foundNode = '';
walkTheDom(rootB, compare);
if (foundNode) {
return foundNode
}
}
compare
seems to be missing it's body. Have you made an attempt at writing it or what's it's purpose there? \$\endgroup\$ – Mast Oct 7 '15 at 20:17