File tree Expand file tree Collapse file tree 4 files changed +35
-9
lines changed Expand file tree Collapse file tree 4 files changed +35
-9
lines changed Original file line number Diff line number Diff line change 1
1
'use strict'
2
2
3
+ var is = require ( 'unist-util-is' )
4
+
3
5
module . exports = size
4
6
5
- function size ( node ) {
7
+ function size ( node , test ) {
6
8
var children = node && node . children
7
9
var length = ( children && children . length ) || 0
8
- var count = length
10
+ var count = 0
9
11
var index = - 1
12
+ var child
10
13
11
14
while ( ++ index < length ) {
12
- count += size ( children [ index ] )
15
+ child = children [ index ]
16
+
17
+ if ( is ( test , child , index , node ) ) {
18
+ count ++
19
+ }
20
+
21
+ count += size ( child , test )
13
22
}
14
23
15
24
return count
Original file line number Diff line number Diff line change 18
18
"files" : [
19
19
" index.js"
20
20
],
21
- "dependencies" : {},
21
+ "dependencies" : {
22
+ "unist-util-is" : " ^2.1.3"
23
+ },
22
24
"devDependencies" : {
23
25
"browserify" : " ^16.0.0" ,
24
26
"hastscript" : " ^5.0.0" ,
Original file line number Diff line number Diff line change @@ -36,16 +36,25 @@ var tree = h('div', [
36
36
])
37
37
38
38
console .log (size (tree)) // => 11
39
- console .log (size (tree .children [0 ])) // => 7
40
- console .log (size (tree .children [0 ].children [0 ])) // => 0
39
+ console .log (size (tree, ' element' )) // => 5
41
40
```
42
41
43
42
## API
44
43
45
- ### ` size(tree) `
44
+ ### ` size(tree[, test] ) `
46
45
47
- Calculate the number of nodes in [ ` node ` ] [ node ] .
48
- The result is the number of [ exclusive descendants] [ descendant ] .
46
+ Calculate the number of nodes in [ ` tree ` ] [ node ] .
47
+
48
+ ###### Parameters
49
+
50
+ * ` tree ` ([ ` Node ` ] [ node ] ) — [ Tree] [ ] to traverse
51
+ * ` test ` ([ ` Test ` ] [ is ] , optional) — [ ` is ` ] [ is ] -compatible test (such as a
52
+ node type)
53
+
54
+ ##### Returns
55
+
56
+ ` number ` — Number of [ exclusive descendants] [ descendant ] passing ` test ` in
57
+ ` tree ` .
49
58
50
59
## Contribute
51
60
@@ -103,6 +112,10 @@ abide by its terms.
103
112
104
113
[ unist ] : https://github.com/syntax-tree/unist
105
114
115
+ [ is ] : https://github.com/syntax-tree/unist-util-is
116
+
106
117
[ node ] : https://github.com/syntax-tree/unist#node
107
118
119
+ [ tree ] : https://github.com/syntax-tree/unist#tree
120
+
108
121
[ descendant ] : https://github.com/syntax-tree/unist#descendant
Original file line number Diff line number Diff line change @@ -21,5 +21,7 @@ test('unist-util-size', function(t) {
21
21
t . equal ( size ( tree . children [ 0 ] . children [ 1 ] ) , 1 , 'parent of text' )
22
22
t . equal ( size ( tree . children [ 0 ] . children [ 0 ] ) , 0 , 'text node' )
23
23
24
+ t . equal ( size ( tree , 'element' ) , 5 , 'test' )
25
+
24
26
t . end ( )
25
27
} )
You can’t perform that action at this time.
0 commit comments