Skip to content

Commit

Permalink
Refactor code-style
Browse files Browse the repository at this point in the history
*   Add more docs to JSDoc
*   Add support for `null` in input of API types
*   Add type for `GetDefinition`
  • Loading branch information
wooorm committed Jan 26, 2023
1 parent 44a9f62 commit a98ca64
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 12 deletions.
4 changes: 4 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
/**
* @typedef {import('./lib/index.js').GetDefinition} GetDefinition
*/

export {definitions} from './lib/index.js'
35 changes: 23 additions & 12 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,44 @@
/**
* @typedef {import('mdast').Root|import('mdast').Content} Node
* @typedef {import('mdast').Root} Root
* @typedef {import('mdast').Content} Content
* @typedef {import('mdast').Definition} Definition
*/

/**
* @typedef {Root | Content} Node
*
* @callback GetDefinition
* Get a definition by identifier.
* @param {string | null | undefined} [identifier]
* Identifier of definition.
* @returns {Definition | null}
* Definition corresponding to `identifier`, if found.
*/

import {visit} from 'unist-util-visit'

const own = {}.hasOwnProperty

/**
* Find definitions in `node`.
*
* Uses CommonMark precedence, which means that earlier definitions are
* preferred over duplicate later definitions.
*
* @param {Node} node
* @param {Node} tree
* Tree to check.
* @returns {GetDefinition}
* Getter.
*/
export function definitions(node) {
export function definitions(tree) {
/** @type {Record<string, Definition>} */
const cache = Object.create(null)

if (!node || !node.type) {
if (!tree || !tree.type) {
throw new Error('mdast-util-definitions expected node')
}

visit(node, 'definition', (definition) => {
visit(tree, 'definition', (definition) => {
const id = clean(definition.identifier)
if (id && !own.call(cache, id)) {
cache[id] = definition
Expand All @@ -31,20 +47,15 @@ export function definitions(node) {

return definition

/**
* Get a node from the bound definition cache.
*
* @param {string} identifier
* @returns {Definition|null}
*/
/** @type {GetDefinition} */
function definition(identifier) {
const id = clean(identifier)
return id && own.call(cache, id) ? cache[id] : null
}
}

/**
* @param {string} [value]
* @param {string | null | undefined} [value]
* @returns {string}
*/
function clean(value) {
Expand Down

0 comments on commit a98ca64

Please sign in to comment.