Skip to content

Commit d25fe4e

Browse files
committed
add select.one
1 parent c8a1acc commit d25fe4e

File tree

3 files changed

+47
-4
lines changed

3 files changed

+47
-4
lines changed

README.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44

55
[![Build Status][travis-badge]][travis] [![Dependency Status][david-badge]][david]
66

7-
Select unist nodes using css-like selectors.
7+
Select [Unist] nodes with CSS-like selectors.
8+
9+
[unist]: https://github.com/wooorm/unist
810

911
[travis]: https://travis-ci.org/eush77/unist-util-select
1012
[travis-badge]: https://travis-ci.org/eush77/unist-util-select.svg?branch=master
@@ -84,6 +86,12 @@ All the relevant parts of [Selectors Level 3][spec]:
8486

8587
Applies `selector` to `ast`, returns array of matching nodes.
8688

89+
#### `select.one(ast, selector)`
90+
91+
Returns a single node matching `selector`.
92+
93+
Throws an error if node is not found or not unique.
94+
8795
## Install
8896

8997
```

index.js

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

33
var parseSelector = require('./lib/selector'),
4-
select = require('./lib/select');
4+
matchSelector = require('./lib/select');
55

66
var debug = require('debug')('unist-util-select');
77

88

9-
module.exports = function (ast, selector) {
9+
var select = function select (ast, selector) {
1010
debug('Selector: %j', selector);
1111
selector = parseSelector(selector);
1212
debug('AST: %s',
1313
JSON.stringify(selector, null, 2).replace(/(^|\n)/g, '\n '));
14-
return selector ? select[selector.type](selector, ast) : [];
14+
return selector ? matchSelector[selector.type](selector, ast) : [];
1515
};
16+
17+
18+
select.one = function selectOne (ast, selector) {
19+
var nodes = select(ast, selector);
20+
21+
if (!nodes.length) {
22+
throw Error('Node not found by ' + JSON.stringify(selector));
23+
}
24+
if (nodes.length > 1) {
25+
throw Error('Node matched by ' + JSON.stringify(selector) + ' is not unique');
26+
}
27+
28+
return nodes[0];
29+
};
30+
31+
32+
module.exports = select;

test/select-one.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'use strict';
2+
3+
var select = require('..'),
4+
select1 = select.one,
5+
ast = require('./lib/ast')(),
6+
path = require('./lib/path');
7+
8+
var test = require('tape');
9+
10+
11+
test('select.one', function (t) {
12+
t.equal(select1(ast, 'root'), ast);
13+
t.equal(select1(ast, 'blockquote'), select(ast, 'blockquote')[0]);
14+
t.equal(select1(ast, 'table'), select(ast, 'table')[0]);
15+
t.throws(select1.bind(null, ast, 'math'), 'throws when node is not found');
16+
t.throws(select1.bind(null, ast, 'text'), 'throws when node is not unique');
17+
t.end();
18+
});

0 commit comments

Comments
 (0)