Add unist-util-ancestor to list of utilities by gorango · Pull Request #53 · syntax-tree/unist (original) (raw)

Nice!

For performance reasons you might want to not use unist-util-find (in this way). And perhaps also getParents like this.
Right now, for every node, the whole tree is walked many many times.

If possible, it would be muuuch faster to walk the tree once/twice.
Here’s some pseudocode:

const stacks = new Map()

visitParents(tree, (node, parents) => { if (nodesToFind.includes(node)) { stacks.set(node, parents) } })

nodesToFind.forEach(node => { if (!stacks.has(node)) { throw new Error('unist-util-ancestor requires all nodes be contained in the tree') } })

// Somethign like this? let index = -1 let ancestor = tree

// This is broken, maybe you get the gist? while (++index) { const nextAncestor = stacks.get(nodesToFind[0])[index]

const shared = nodesToFind.every(node => stacks.get(node)[index] === nextAncestor)

// To do: exit if there are no nodes left on stacks.

if (shared) { ancestor = nextAncestor } else { break } }