JSPM

  • Created
  • Published
  • Downloads 18585
  • Score
    100M100P100Q152980F
  • License MIT

Utility library to traverse AST

Package Exports

  • ast-monkey-traverse

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (ast-monkey-traverse) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

ast-monkey-traverse

Utility library to traverse AST

Install

npm i ast-monkey-traverse

Quick Take

import { strict as assert } from "assert";
import traverse from "ast-monkey-traverse";

const paths = [];
const source = {
  a: {
    foo: {
      bar: [
        {
          foo: "c",
        },
      ],
      d: {
        e: {
          foo: "f",
        },
      },
    },
  },
};

traverse(source, (key, val, innerObj) => {
  // if currently an object is traversed, you get both "key" and "val"
  // if it's array, only "key" is present, "val" is undefined
  const current = val !== undefined ? val : key;
  if (
    // it's object (not array)
    val !== undefined &&
    // and has the key we need
    key === "foo"
  ) {
    // push the path to array in the outer scope
    paths.push(innerObj.path);
  }
  return current;
});

// notice object-path notation "a.foo.bar.0.foo" - array segments use dots too:
assert.deepEqual(paths, ["a.foo", "a.foo.bar.0.foo", "a.foo.d.e.foo"]);

Documentation

Please visit codsen.com for a full description of the API and examples.

Licence

MIT License

Copyright (c) 2010-2020 Roy Revelt and other contributors

ok codsen star