convert.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 'use strict'
  2. module.exports = convert
  3. function convert(test) {
  4. if (typeof test === 'string') {
  5. return typeFactory(test)
  6. }
  7. if (test === null || test === undefined) {
  8. return ok
  9. }
  10. if (typeof test === 'object') {
  11. return ('length' in test ? anyFactory : matchesFactory)(test)
  12. }
  13. if (typeof test === 'function') {
  14. return test
  15. }
  16. throw new Error('Expected function, string, or object as test')
  17. }
  18. function convertAll(tests) {
  19. var results = []
  20. var length = tests.length
  21. var index = -1
  22. while (++index < length) {
  23. results[index] = convert(tests[index])
  24. }
  25. return results
  26. }
  27. // Utility assert each property in `test` is represented in `node`, and each
  28. // values are strictly equal.
  29. function matchesFactory(test) {
  30. return matches
  31. function matches(node) {
  32. var key
  33. for (key in test) {
  34. if (node[key] !== test[key]) {
  35. return false
  36. }
  37. }
  38. return true
  39. }
  40. }
  41. function anyFactory(tests) {
  42. var checks = convertAll(tests)
  43. var length = checks.length
  44. return matches
  45. function matches() {
  46. var index = -1
  47. while (++index < length) {
  48. if (checks[index].apply(this, arguments)) {
  49. return true
  50. }
  51. }
  52. return false
  53. }
  54. }
  55. // Utility to convert a string into a function which checks a given node’s type
  56. // for said string.
  57. function typeFactory(test) {
  58. return type
  59. function type(node) {
  60. return Boolean(node && node.type === test)
  61. }
  62. }
  63. // Utility to return true.
  64. function ok() {
  65. return true
  66. }