Skip to content

Commit 336dcfc

Browse files
committed
Add support for passing a test
1 parent 927e741 commit 336dcfc

File tree

4 files changed

+35
-9
lines changed

4 files changed

+35
-9
lines changed

index.js

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,24 @@
11
'use strict'
22

3+
var is = require('unist-util-is')
4+
35
module.exports = size
46

5-
function size(node) {
7+
function size(node, test) {
68
var children = node && node.children
79
var length = (children && children.length) || 0
8-
var count = length
10+
var count = 0
911
var index = -1
12+
var child
1013

1114
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)
1322
}
1423

1524
return count

package.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@
1818
"files": [
1919
"index.js"
2020
],
21-
"dependencies": {},
21+
"dependencies": {
22+
"unist-util-is": "^2.1.3"
23+
},
2224
"devDependencies": {
2325
"browserify": "^16.0.0",
2426
"hastscript": "^5.0.0",

readme.md

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,16 +36,25 @@ var tree = h('div', [
3636
])
3737

3838
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
4140
```
4241

4342
## API
4443

45-
### `size(tree)`
44+
### `size(tree[, test])`
4645

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`.
4958

5059
## Contribute
5160

@@ -103,6 +112,10 @@ abide by its terms.
103112

104113
[unist]: https://github.com/syntax-tree/unist
105114

115+
[is]: https://github.com/syntax-tree/unist-util-is
116+
106117
[node]: https://github.com/syntax-tree/unist#node
107118

119+
[tree]: https://github.com/syntax-tree/unist#tree
120+
108121
[descendant]: https://github.com/syntax-tree/unist#descendant

test.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,7 @@ test('unist-util-size', function(t) {
2121
t.equal(size(tree.children[0].children[1]), 1, 'parent of text')
2222
t.equal(size(tree.children[0].children[0]), 0, 'text node')
2323

24+
t.equal(size(tree, 'element'), 5, 'test')
25+
2426
t.end()
2527
})

0 commit comments

Comments
 (0)