Giter Club home page Giter Club logo

unist-util-is's Introduction

unist-util-is

Build Coverage Downloads Size Sponsors Backers Chat

unist utility to check if nodes pass a test.

Contents

What is this?

This package is a small utility that checks that a node is a certain node.

When should I use this?

Use this small utility if you find yourself repeating code for checking what nodes are.

A similar package, hast-util-is-element, works on hast elements.

For more advanced tests, unist-util-select can be used to match against CSS selectors.

Install

This package is ESM only. In Node.js (version 16+), install with npm:

npm install unist-util-is

In Deno with esm.sh:

import {is} from 'https://esm.sh/unist-util-is@6'

In browsers with esm.sh:

<script type="module">
  import {is} from 'https://esm.sh/unist-util-is@6?bundle'
</script>

Use

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

const node = {type: 'strong'}
const parent = {type: 'paragraph', children: [node]}

is() // => false
is({children: []}) // => false
is(node) // => true
is(node, 'strong') // => true
is(node, 'emphasis') // => false

is(node, node) // => true
is(parent, {type: 'paragraph'}) // => true
is(parent, {type: 'strong'}) // => false

is(node, test) // => false
is(node, test, 4, parent) // => false
is(node, test, 5, parent) // => true

function test(node, n) {
  return n === 5
}

API

This package exports the identifiers convert and is. There is no default export.

is(node[, test[, index, parent[, context]]])

Check if node is a Node and whether it passes the given test.

Parameters
  • node (unknown, optional) — thing to check, typically Node
  • test (Test, optional) — a test for a specific element
  • index (number, optional) — the node’s position in its parent
  • parent (Node, optional) — the node’s parent
  • context (unknown, optional) — context object (this) to call test with
Returns

Whether node is a Node and passes a test (boolean).

Throws

When an incorrect test, index, or parent is given. There is no error thrown when node is not a node.

convert(test)

Generate a check from a test.

Useful if you’re going to test many nodes, for example when creating a utility where something else passes a compatible test.

The created function is a bit faster because it expects valid input only: a node, index, and parent.

Parameters
  • test (Test, optional) — a test for a specific node
Returns

A check (Check).

Check

Check that an arbitrary value is a node (TypeScript type).

Parameters
  • this (unknown, optional) — context object (this) to call test with
  • node (unknown) — anything (typically a node)
  • index (number, optional) — the node’s position in its parent
  • parent (Node, optional) — the node’s parent
Returns

Whether this is a node and passes a test (boolean).

Test

Check for an arbitrary node (TypeScript type).

Type
type Test =
  | Array<Record<string, unknown> | TestFunction | string>
  | Record<string, unknown>
  | TestFunction
  | string
  | null
  | undefined

Checks that the given thing is a node, and then:

  • when string, checks that the node has that tag name
  • when function, see TestFunction
  • when object, checks that all keys in test are in node, and that they have (strictly) equal values
  • when Array, checks if one of the subtests pass

TestFunction

Check if a node passes a test (TypeScript type).

Parameters
  • node (Node) — a node
  • index (number or undefined) — the node’s position in its parent
  • parent (Node or undefined) — the node’s parent
Returns

Whether this node passes the test (boolean, optional).

Examples

Example of convert

import {u} from 'unist-builder'
import {convert} from 'unist-util-is'

const test = convert('leaf')

const tree = u('tree', [
  u('node', [u('leaf', '1')]),
  u('leaf', '2'),
  u('node', [u('leaf', '3'), u('leaf', '4')]),
  u('leaf', '5')
])

const leafs = tree.children.filter(function (child, index) {
  return test(child, index, tree)
})

console.log(leafs)

Yields:

[{type: 'leaf', value: '2'}, {type: 'leaf', value: '5'}]

Types

This package is fully typed with TypeScript. It exports the additional types Check, Test, TestFunction.

Compatibility

Projects maintained by the unified collective are compatible with maintained versions of Node.js.

When we cut a new major release, we drop support for unmaintained versions of Node. This means we try to keep the current release line, unist-util-is@^6, compatible with Node.js 16.

Related

Contribute

See contributing.md in syntax-tree/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT © Titus Wormer

unist-util-is's People

Contributors

arcanis avatar christianmurphy avatar greenkeeperio-bot avatar roang-zero1 avatar wooorm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unist-util-is's Issues

`node` first, `test` second

Unist utilities operate on nodes. Makes more sense passing the Node first. Then the test. Optionally other stuff.

Import types from mdast or add @types/unist to devDeps

I think those types should probably be imported from 'mdast'
https://github.com/syntax-tree/unist-util-is/blob/master/index.d.ts#L3
Or as mentioned in the title @types/unist needs to be added to the dependencies

I'm trying to update to Yarn2 and this popped up

../../.yarn/cache/unist-util-is-npm-4.0.1-2754fc9f60-1.zip/node_modules/unist-util-is/index.d.ts(3,28): error TS2307: Cannot find module 'unist'.

and as Yarn2 is really specific about deps my only guess right now is this issue 😁

(edited by @wooorm to refactor formatting)

Improve documentation on is() and is.convert()() not beein equivalent

is and is.convert()() do not have the same behavior.

The function created through convert() do not have the same results as calling is() directly, even when using the same tests.

I've rewritten all tests from is() to convert()() at Roang-zero1/unist-util-is/tree/convert-test. Running these tests failes 14 tests (e.g. for invalid index).

Steps to reproduce

git clone https://github.com/Roang-zero1/unist-util-is.git
npm install
npm run test

Expected behaviour

From my understanding is() and convert()() should be equivalent.

Actual behaviour

is(node, null, -1) throws and error while

const testNull = convert(null)
testNull(node, -1)

returns undefined.

type TestFunction is a type predicate, not a generic predicate

Subject of the issue

I'm looking at this:

unist-util-is/index.d.ts

Lines 29 to 33 in 8c0a649

type TestFunction<T extends Node> = (
node: unknown,
index?: number,
parent?: Parent
) => node is T

As I read the docs, and the code, the test is "converted" here:

unist-util-is/convert.js

Lines 18 to 20 in 8c0a649

if (typeof test === 'function') {
return test
}

As I understand the docs I can have a function that tests the content of the node and returns boolean whether the node is a match for my conditions or not.

However, as I read the types, my function must be a type predicate that asserts whether or not my node is of a given TypeScript type.

I'm definitely not a TypeScript expert, so I may have gotten something wrong here. If so, apologies. If not, I can try to add an additional type test.

Your environment

v 4.0.1

Steps to reproduce

import { Node, Parent } from "unist";
import visit from "unist-util-visit";

export const insertBefore = (
  tree: Parent,
  predicate: (node: Node, index?: number, parent?: Parent) => boolean,
  transform: (node: Node) => Node
) => {
  visit(tree, predicate, (node, index, parent) => {});
};

Expected behaviour

I believe that my example above would run in javascript, but fails type checking.

Actual behaviour

No overload matches this call.
  Overload 1 of 2, '(tree: Node, test: string | any[] | Partial<Node> | TestFunction<Node>, visitor: Visitor<Node>, reverse?: boolean | undefined): void', gave the following error.
    Argument of type '(node: Node, index?: number | undefined, parent?: ParentNode | undefined) => boolean' is not assignable to parameter of type 'string | any[] | Partial<Node> | TestFunction<Node>'.
      Type '(node: Node, index?: number | undefined, parent?: ParentNode | undefined) => boolean' is not assignable to type 'TestFunction<Node>'.
        Types of parameters 'node' and 'node' are incompatible.
          Type 'unknown' is not assignable to type 'Node'.
  Overload 2 of 2, '(tree: Node, visitor: Visitor<Node>, reverse?: boolean | undefined): void', gave the following error.
    Argument of type '(node: Node, index?: number | undefined, parent?: ParentNode | undefined) => boolean' is not assignable to parameter of type 'Visitor<Node>'.
      Types of parameters 'node' and 'node' are incompatible.
        Type 'Node' is missing the following properties from type 'Node': baseURI, childNodes, firstChild, isConnected, and 47 more.  TS2769

Add property tests / deep equals

...and drop node identity tests.

With the advent of HAST, passing {tagName: 'article'} would be a very useful addition. But, this interferes with node identity tests. As the latter is quite easily done inside the Function form of test, I believe dropping it is an OK and necessary choice.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.