我最近面试了 Facebook 的前端工程师职位。对于我的手机屏幕,我有以下问题:给定一个来自 DOM 树的节点,从相同的 DOM 树中找到位于相同位置的节点。为清楚起见,请参见下图。
A B
O O
|\ |\
O O O O
/|\ /|\
O O O O O O
\ \
O O
这是我的解决方案,我想知道我可以做些什么来改进/优化它。
var rootA, rootB;
function findNodeB(nodeA) {
// Variable to store path up the DOM tree
var travelPath = [];
// Method to travel up the DOM tree and store path to exact node
var establishPath = function(travelNode) {
// If we have reached the top level node we want to return
// otherwise we travel up another level on the tree
if (travelNode === rootA) {
return;
} else {
establishPath(travelNode.parentNode);
}
// We store the index of current child in our path
var index = travelNode.parentNode.childNodes.indexOf(travelNode);
travelPath.push(index);
}
var traverseTree = function(bTreeNode, path) {
if(path.length === 0) {
return bTreeNode;
} else {
traverseTree(bTreeNode.childNodes[path.pop()], path);
}
}
establishPath(rootB, nodeA);
return traverseTree(rootB, travelPath);
}