Skip to content

Commit b4d92b6

Browse files
committed
Add support for passing a child
1 parent c43f6df commit b4d92b6

File tree

3 files changed

+29
-4
lines changed

3 files changed

+29
-4
lines changed

index.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,14 @@ function isLiteral(parent, index) {
8989
throw new Error('Parent must be a node')
9090
}
9191

92+
if (index !== null && typeof index === 'object' && 'type' in index) {
93+
index = parent.children.indexOf(index)
94+
95+
if (index === -1) {
96+
throw new Error('Node must be a child of `parent`')
97+
}
98+
}
99+
92100
if (isNaN(index)) {
93101
throw new Error('Index must be a number')
94102
}

readme.md

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,10 +75,10 @@ quux
7575

7676
## API
7777

78-
### `isLiteral(parent, index)`
78+
### `isLiteral(parent, index|child)`
7979

80-
Check if the node in `parent` at `position` is enclosed
81-
by matching delimiters.
80+
Check if the `child` in `parent` is enclosed by matching delimiters.
81+
If `index` is given, the [child][] of `parent` at that [index][] is checked.
8282

8383
For example, `foo` is literal in the following samples:
8484

@@ -141,3 +141,7 @@ abide by its terms.
141141
[coc]: https://github.com/syntax-tree/.github/blob/master/code-of-conduct.md
142142

143143
[nlcst]: https://github.com/syntax-tree/nlcst
144+
145+
[index]: https://github.com/syntax-tree/unist#index
146+
147+
[child]: https://github.com/syntax-tree/unist#child

test.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,22 @@ test('isLiteral()', function(t) {
2828
isLiteral({children: []})
2929
},
3030
/Index must be a number/,
31-
'should throw without index'
31+
'should throw without node'
3232
)
3333

34+
t.throws(
35+
function() {
36+
isLiteral({children: []}, {type: 'a'})
37+
},
38+
/Node must be a child of `parent`/,
39+
'should throw if `node` is not in `parent`'
40+
)
41+
42+
t.doesNotThrow(function() {
43+
var n = {type: 'a'}
44+
isLiteral({children: [n]}, n)
45+
}, 'should not throw if `node` is in `parent`')
46+
3447
t.doesNotThrow(function() {
3548
process('Well? Ha! Funky', function(node, index, parent) {
3649
assert.strictEqual(isLiteral(parent, index), false)

0 commit comments

Comments
 (0)