33 lines
791 B
JavaScript
33 lines
791 B
JavaScript
'use strict'
|
|
|
|
var convert = require('./convert')
|
|
|
|
module.exports = is
|
|
|
|
is.convert = convert
|
|
|
|
// Assert if `test` passes for `node`.
|
|
// When a `parent` node is known the `index` of node should also be given.
|
|
function is(node, test, index, parent, context) {
|
|
var check = convert(test)
|
|
|
|
if (
|
|
index != null &&
|
|
(typeof index !== 'number' || index < 0 || index === Infinity)
|
|
) {
|
|
throw new Error('Expected positive finite index')
|
|
}
|
|
|
|
if (parent != null && (!is(parent) || !parent.children)) {
|
|
throw new Error('Expected parent node')
|
|
}
|
|
|
|
if ((parent == null) !== (index == null)) {
|
|
throw new Error('Expected both parent and index')
|
|
}
|
|
|
|
return node && node.type && typeof node.type === 'string'
|
|
? Boolean(check.call(context, node, index, parent))
|
|
: false
|
|
}
|