index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * @typedef {import('mdast').Definition} Definition
  3. * @typedef {import('mdast').Nodes} Nodes
  4. */
  5. /**
  6. * @callback GetDefinition
  7. * Get a definition by identifier.
  8. * @param {string | null | undefined} [identifier]
  9. * Identifier of definition (optional).
  10. * @returns {Definition | undefined}
  11. * Definition corresponding to `identifier` or `null`.
  12. */
  13. import {visit} from 'unist-util-visit'
  14. /**
  15. * Find definitions in `tree`.
  16. *
  17. * Uses CommonMark precedence, which means that earlier definitions are
  18. * preferred over duplicate later definitions.
  19. *
  20. * @param {Nodes} tree
  21. * Tree to check.
  22. * @returns {GetDefinition}
  23. * Getter.
  24. */
  25. export function definitions(tree) {
  26. /** @type {Map<string, Definition>} */
  27. const cache = new Map()
  28. if (!tree || !tree.type) {
  29. throw new Error('mdast-util-definitions expected node')
  30. }
  31. visit(tree, 'definition', function (definition) {
  32. const id = clean(definition.identifier)
  33. if (id && !cache.get(id)) {
  34. cache.set(id, definition)
  35. }
  36. })
  37. return definition
  38. /** @type {GetDefinition} */
  39. function definition(identifier) {
  40. const id = clean(identifier)
  41. return cache.get(id)
  42. }
  43. }
  44. /**
  45. * @param {string | null | undefined} [value]
  46. * @returns {string}
  47. */
  48. function clean(value) {
  49. return String(value || '').toUpperCase()
  50. }