ensure that nodes are only traversed once per context

This commit is contained in:
Sebastian McKenzie 2015-03-28 04:34:05 +11:00
parent afedfe15ae
commit 3f144e6e74
2 changed files with 13 additions and 10 deletions

View File

@ -18,9 +18,10 @@ export default class TraversalContext {
// nothing to traverse!
if (nodes.length === 0) return false;
var visited = [];
var queue = this.queue = [];
var stop = false;
var done = [];
// build up initial queue
for (let i = 0; i < nodes.length; i++) {
@ -29,7 +30,12 @@ export default class TraversalContext {
// visit the queue
for (let i = 0; i < queue.length; i++) {
if (queue[i].visit()) {
var path = queue[i];
if (visited.indexOf(path.node) >= 0) continue;
visited.push(path.node);
if (path.visit()) {
stop = true;
break;
}

View File

@ -97,6 +97,7 @@ export default class TraversalPath {
_containerInsertAfter(nodes) {
this.updateSiblingKeys(this.key + 1, nodes.length);
for (var i = 0; i < nodes.length; i++) {
var to = this.key + 1 + i;
this.container.splice(to, 0, nodes[i]);
@ -222,7 +223,7 @@ export default class TraversalPath {
replaceInline(nodes) {
if (Array.isArray(nodes)) {
if (Array.isArray(this.container)) {
this._verifyNodeList("replaceInline", nodes);
this._verifyNodeList(nodes);
this._containerInsertAfter(nodes);
return this.remove();
} else {
@ -233,19 +234,15 @@ export default class TraversalPath {
}
}
_verifyNodeList(key, nodes) {
if (nodes.indexOf(this.node) >= 0) {
// todo: possibly check for inclusion of current node and yell at the user as it's an anti-pattern
}
_verifyNodeList(nodes) {
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (!node) throw new Error(`Falsy node passed to \`path.${key}()\` with the index of ${i}`);
if (!node) throw new Error(`Node list has falsy node with the index of ${i}`);
}
}
replaceWithMultiple(nodes: Array<Object>) {
this._verifyNodeList("replaceWithMultiple", nodes);
this._verifyNodeList(nodes);
t.inheritsComments(nodes[0], this.node);
this.container[this.key] = null;
this.insertAfter(nodes);