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