blob: f18d416e08d214dfab65f3dadc9f5af279f34392 [file] [log] [blame]
'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.
// eslint-disable-next-line max-params
function is(node, test, index, parent, context) {
var hasParent = parent !== null && parent !== undefined
var hasIndex = index !== null && index !== undefined
var check = convert(test)
if (
hasIndex &&
(typeof index !== 'number' || index < 0 || index === Infinity)
) {
throw new Error('Expected positive finite index or child node')
}
if (hasParent && (!is(parent) || !parent.children)) {
throw new Error('Expected parent node')
}
if (!node || !node.type || typeof node.type !== 'string') {
return false
}
if (hasParent !== hasIndex) {
throw new Error('Expected both parent and index')
}
return Boolean(check.call(context, node, index, parent))
}