Coder Social home page Coder Social logo

syntax-tree / unist-util-map Goto Github PK

View Code? Open in Web Editor NEW
35.0 9.0 4.0 123 KB

utility to create a new tree by mapping all nodes

Home Page: https://unifiedjs.com

License: MIT License

JavaScript 86.75% TypeScript 13.25%
unist util syntax-tree map unist-util

unist-util-map's Introduction

unist-util-map

Build Coverage Downloads Size Sponsors Backers Chat

unist utility to create a new tree by mapping all nodes with a given function.

Contents

What is this?

This is a small utility that helps you make new trees.

When should I use this?

You can use this utility to create a new tree by mapping all nodes with a given function. Creating new trees like this can lead to performance problems, as it creates new objects for every node. When dealing with potentially large trees, and relatively few changes, use unist-util-visit (or unist-util-visit-parents) instead.

To remove certain nodes, you can also walk the tree with unist-util-visit, or use unist-util-filter (clones the tree instead of mutating) or unist-util-remove (mutates). To create trees, use unist-builder.

Install

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

npm install unist-util-map

In Deno with esm.sh:

import {map} from 'https://esm.sh/unist-util-map@4'

In browsers with esm.sh:

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

Use

import {u} from 'unist-builder'
import {map} from 'unist-util-map'

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

const next = map(tree, function (node) {
  return node.type === 'leaf'
    ? Object.assign({}, node, {value: 'CHANGED'})
    : node
})

console.dir(next, {depth: undefined})

Yields:

{
  type: 'tree',
  children: [
    {type: 'leaf', value: 'CHANGED'},
    {type: 'node', children: [{type: 'leaf', value: 'CHANGED'}]},
    {type: 'void'},
    {type: 'leaf', value: 'CHANGED'}
  ]
}

👉 Note: next is a changed clone and tree is not mutated.

API

This package exports the identifier map. There is no default export.

map(tree, mapFunction)

Create a new tree by mapping all nodes with the given function.

Parameters
  • tree (Node) — tree to map
  • mapFunction (MapFunction) — function called with a node, its index, and its parent to produce a new node
Returns

New mapped tree (Node).

MapFunction

Function called with a node, its index, and its parent to produce a new node (TypeScript type).

Parameters
  • node (Node) — node to map
  • index (number or undefined) — index of node in parent (if any)
  • parent (Node or undefined) — parent of node
Returns

New mapped node (Node).

The children on the returned node are not used. If the original node has children, those are mapped instead.

Types

This package is fully typed with TypeScript. It exports the additional type MapFunction.

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-map@^4, 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 © azu

unist-util-map's People

Contributors

azu avatar christianmurphy avatar jounqin avatar juanm04 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  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unist-util-map's Issues

Support async mapFn

Support async mapFn

For asynchronous operations it'd be great if we could pass an async function as the mapFn e.g.

map(tree, async (node) => {
  await asyncFn()
})

Problem

Can't perform async operations when mapping over nodes.

Expected behavior

Should be able to use await inside an async mapFn

Alternatives

Visit nodes and perform async operations in the transformer.

unist-util-map types Node and MapFunction stopped to be exported between v3 and v3.1.1

Initial checklist

Affected packages and versions

unist-util-map 3.1.1

Link to runnable example

https://stackblitz.com/edit/typescript-gjwbvb?file=index.ts

Steps to reproduce

Start a new sandbox and install the latest unist-util-map v3.1.1:
https://stackblitz.com/edit/typescript-gjwbvb?file=index.ts
notice the MapFunction and Node (and Parent) types are not exported any more

but they used to be exported on v3:
https://stackblitz.com/edit/typescript-qh1hrn?file=index.ts

which means, we introduced a breaking semver change during a minor bump!

Now, other consumers such as remark-directive-rehype are importing the unist-util-map with a caret semver, which causes them to break on fresh installs (stale lockfiles still contain working v3 references, so everything seems fine for those who have stale lockfiles and their package manager uses exact stale version v3)
https://github.com/IGassmann/remark-directive-rehype/blob/5dec9b98dcf8e071d2bd5b776f96123f459492f9/package.json#L34

Expected behavior

Let's restore the old type exports, specifically:

export type Node = import('unist').Node
export type Parent = import('unist').Parent
export type MapFunction = (node: Node, index?: number, parent?: Parent) => Node

If we really want to remove the types, then issue a patch with types restored and bump the major version, publishing this program with types removed.

Generally, to prevent mishaps like this, it's best to migrate the source to .ts source files and let the TypeScript generate the types automatically, using a bundler. The JSDoc can be used for examples etc but not as a source of type definitions. That's the setup I use myself, I use esbuild to bundle ESM (and sometimes optionally IIFE too) and rollup with rollup-plugin-dts to bundle up the type definition files. The JSDoc-based types from .js sources are a liability.

Actual behavior

type exports are missing currently

Affected runtime and version

n/a

Affected package manager and version

tested on both yarn and npm

Affected OS and version

n/a

Build and bundle tools

Other (please specify in steps to reproduce)

Cannot change `children` field

Initial checklist

Problem

I replaced the �children field but the returned object did not reflect the change.

Solution

I think this library should provide a means to change the children filed to a new value(new reference).

Alternatives

.

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.