|
1 |
| -'use strict'; |
| 1 | +'use strict' |
2 | 2 |
|
3 |
| -var is = require('unist-util-is'); |
| 3 | +var is = require('unist-util-is') |
4 | 4 |
|
| 5 | +module.exports = remove |
5 | 6 |
|
6 |
| -module.exports = function (ast, opts, predicate) { |
7 |
| - if (arguments.length == 2) { |
8 |
| - predicate = opts; |
9 |
| - opts = {}; |
| 7 | +function remove(ast, opts, test) { |
| 8 | + var cascade |
| 9 | + |
| 10 | + if (!test) { |
| 11 | + test = opts |
| 12 | + opts = {} |
10 | 13 | }
|
11 | 14 |
|
12 |
| - opts.cascade = opts.cascade || opts.cascade === undefined; |
| 15 | + cascade = opts.cascade |
| 16 | + cascade = cascade === null || cascade === undefined ? true : cascade |
| 17 | + |
| 18 | + return preorder(ast, null, null) |
13 | 19 |
|
14 | 20 | // Check and remove nodes recursively in preorder.
|
15 | 21 | // For each composite node, modify its children array in-place.
|
16 |
| - return (function preorder (node, nodeIndex, parent) { |
17 |
| - if (is(predicate, node, nodeIndex, parent)) { |
18 |
| - return null; |
| 22 | + function preorder(node, nodeIndex, parent) { |
| 23 | + var children |
| 24 | + var length |
| 25 | + var index |
| 26 | + var position |
| 27 | + var child |
| 28 | + |
| 29 | + if (is(test, node, nodeIndex, parent)) { |
| 30 | + return null |
19 | 31 | }
|
20 |
| - if (!node.children || !node.children.length) { |
21 |
| - return node; |
| 32 | + |
| 33 | + children = node.children |
| 34 | + |
| 35 | + if (!children || children.length === 0) { |
| 36 | + return node |
22 | 37 | }
|
23 | 38 |
|
24 | 39 | // Move all living children to the beginning of the children array.
|
| 40 | + position = 0 |
| 41 | + length = children.length |
| 42 | + index = -1 |
25 | 43 |
|
26 |
| - var length = 0; |
27 |
| - |
28 |
| - for (var index = 0; index < node.children.length; ++index) { |
29 |
| - var child = preorder(node.children[index], index, node); |
| 44 | + while (++index < length) { |
| 45 | + child = preorder(children[index], index, node) |
30 | 46 |
|
31 | 47 | if (child) {
|
32 |
| - node.children[length++] = child; |
| 48 | + children[position++] = child |
33 | 49 | }
|
34 | 50 | }
|
35 | 51 |
|
36 |
| - if (!length && opts.cascade) { |
37 |
| - // Cascade delete. |
38 |
| - return null; |
| 52 | + // Cascade delete. |
| 53 | + if (cascade && position === 0) { |
| 54 | + return null |
39 | 55 | }
|
40 | 56 |
|
41 |
| - node.children.length = length; |
42 |
| - return node; |
43 |
| - }(ast, null, null)); |
44 |
| -}; |
| 57 | + // Drop other nodes. |
| 58 | + children.length = position |
| 59 | + |
| 60 | + return node |
| 61 | + } |
| 62 | +} |
0 commit comments