diff --git a/src/estree-walker.js b/src/estree-walker.js index e1b01df..188b59e 100644 --- a/src/estree-walker.js +++ b/src/estree-walker.js @@ -2,6 +2,7 @@ function walk(ast, { enter, leave }) { return visit(ast, null, enter, leave); } +let remove_count = 0; let should_skip = false; let should_remove = false; let replacement = null; @@ -24,7 +25,7 @@ function replace(parent, prop, index, node) { function remove(parent, prop, index) { if (parent) { if (index !== null) { - parent[prop].splice(index, 1); + parent[prop].splice(index - remove_count, 1); } else { delete parent[prop]; } @@ -78,14 +79,18 @@ function visit( } else if (Array.isArray(value)) { + const _remove_count = remove_count; + remove_count = 0; for (let j = 0, k = 0; j < value.length; j += 1, k += 1) { if (value[j] !== null && typeof value[j].type === 'string') { if (!visit(value[j], node, enter, leave, key, k)) { // removed j--; + remove_count++; } } } + remove_count = _remove_count; } else if (value !== null && typeof value.type === 'string') { diff --git a/src/index.ts b/src/index.ts index d39e22d..51a7e67 100644 --- a/src/index.ts +++ b/src/index.ts @@ -23,6 +23,7 @@ export function walk(ast: Node, { enter, leave }: Walker) { return visit(ast, null, enter, leave); } +let remove_count = 0; let should_skip = false; let should_remove = false; let replacement: Node = null; @@ -45,7 +46,7 @@ function replace(parent: any, prop: string, index: number, node: Node) { function remove(parent: any, prop: string, index: number) { if (parent) { if (index !== null) { - parent[prop].splice(index, 1); + parent[prop].splice(index - remove_count, 1); } else { delete parent[prop]; } @@ -99,14 +100,18 @@ function visit( } else if (Array.isArray(value)) { + const _remove_count = remove_count; + remove_count = 0; for (let j = 0, k = 0; j < value.length; j += 1, k += 1) { if (value[j] !== null && typeof value[j].type === 'string') { if (!visit(value[j], node, enter, leave, key, k)) { // removed j--; + remove_count++; } } } + remove_count = _remove_count; } else if (value !== null && typeof value.type === 'string') { diff --git a/test/test.ts b/test/test.ts index 12d9e65..cbcd3e0 100644 --- a/test/test.ts +++ b/test/test.ts @@ -337,18 +337,17 @@ describe('estree-walker', () => { [phase](node, parent, key, index) { if (node.type === 'VariableDeclarator') { visitedIndex.push(index); - if (index === 1) { + if (node.id.name === 'b' || node.id.name === 'a') { this.remove(); } } } }); - assert.equal(ast.body[0].declarations.length, 2); + assert.equal(ast.body[0].declarations.length, 1); assert.equal(visitedIndex.length, 3); assert.deepEqual(visitedIndex, [0, 1, 2]); - assert.equal(ast.body[0].declarations[0].id.name, 'a'); - assert.equal(ast.body[0].declarations[1].id.name, 'c'); + assert.equal(ast.body[0].declarations[0].id.name, 'c'); }); }) });