index.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict'
  2. var visit = require('unist-util-visit')
  3. module.exports = getDefinitionFactory
  4. var own = {}.hasOwnProperty
  5. // Get a definition in `node` by `identifier`.
  6. function getDefinitionFactory(node, options) {
  7. return getterFactory(gather(node, options))
  8. }
  9. // Gather all definitions in `node`
  10. function gather(node, options) {
  11. var cache = {}
  12. if (!node || !node.type) {
  13. throw new Error('mdast-util-definitions expected node')
  14. }
  15. visit(node, 'definition', options && options.commonmark ? commonmark : normal)
  16. return cache
  17. function commonmark(definition) {
  18. var id = normalise(definition.identifier)
  19. if (!own.call(cache, id)) {
  20. cache[id] = definition
  21. }
  22. }
  23. function normal(definition) {
  24. cache[normalise(definition.identifier)] = definition
  25. }
  26. }
  27. // Factory to get a node from the given definition-cache.
  28. function getterFactory(cache) {
  29. return getter
  30. // Get a node from the bound definition-cache.
  31. function getter(identifier) {
  32. var id = identifier && normalise(identifier)
  33. return id && own.call(cache, id) ? cache[id] : null
  34. }
  35. }
  36. function normalise(identifier) {
  37. return identifier.toUpperCase()
  38. }