index.js 948 B

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict'
  2. var convert = require('./convert')
  3. module.exports = is
  4. is.convert = convert
  5. // Assert if `test` passes for `node`.
  6. // When a `parent` node is known the `index` of node should also be given.
  7. // eslint-disable-next-line max-params
  8. function is(node, test, index, parent, context) {
  9. var hasParent = parent !== null && parent !== undefined
  10. var hasIndex = index !== null && index !== undefined
  11. var check = convert(test)
  12. if (
  13. hasIndex &&
  14. (typeof index !== 'number' || index < 0 || index === Infinity)
  15. ) {
  16. throw new Error('Expected positive finite index or child node')
  17. }
  18. if (hasParent && (!is(parent) || !parent.children)) {
  19. throw new Error('Expected parent node')
  20. }
  21. if (!node || !node.type || typeof node.type !== 'string') {
  22. return false
  23. }
  24. if (hasParent !== hasIndex) {
  25. throw new Error('Expected both parent and index')
  26. }
  27. return Boolean(check.call(context, node, index, parent))
  28. }