Unist Utility to Find a Node Before Another

4.0.1 · active · verified Sun Apr 19

unist-util-find-before is a specialized utility within the unified ecosystem designed to locate the first node that appears before a specified node or index within a parent node's children. It's currently at version 4.0.1 and follows the unified collective's release cadence, typically aligning major releases with Node.js LTS versions and dropping support for unmaintained Node.js versions. While the core functionality of iterating and finding a node could be implemented manually, this package provides a robust, well-tested, and type-safe solution that integrates seamlessly with other `unist` utilities, promoting consistency and reducing boilerplate when working with abstract syntax trees (ASTs). Its key differentiators include its small size, strong TypeScript support, and adherence to the unified project's compatibility standards, making it a reliable choice for AST manipulation tasks where precise node location is required.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import and use `findBefore` to locate nodes before a target node or index, with and without a `test` function, within a sample Unist AST.

import { u } from 'unist-builder';
import { findBefore } from 'unist-util-find-before';

// Create a sample Unist tree
const tree = u('root', [
  u('paragraph', [u('text', 'Hello')]),
  u('heading', { depth: 1 }, [u('text', 'Title')]),
  u('list', [
    u('listItem', [u('text', 'Item 1')]),
    u('listItem', [u('text', 'Item 2')])
  ]),
  u('code', { lang: 'js' }, 'console.log("Code")'),
  u('paragraph', [u('text', 'World')])
]);

// Find the 'code' node
const codeNode = tree.children?.[3];

if (codeNode) {
  // Find the first 'paragraph' node before the 'code' node
  const prevParagraph = findBefore(tree, codeNode, 'paragraph');
  console.log('Previous paragraph node:', prevParagraph ? prevParagraph.type : 'Not found');

  // Find the first 'heading' node before the 4th child (index 3, which is the code node)
  const prevHeadingByIndex = findBefore(tree, 3, 'heading');
  console.log('Previous heading node by index:', prevHeadingByIndex ? prevHeadingByIndex.type : 'Not found');

  // Find the first node of any type before the 'code' node
  const anyPrevNode = findBefore(tree, codeNode);
  console.log('Any previous node:', anyPrevNode ? anyPrevNode.type : 'Not found');
}

/* Expected output:
Previous paragraph node: paragraph
Previous heading node by index: heading
Any previous node: list
*/

view raw JSON →