nodejs-lockfile-parser icon indicating copy to clipboard operation
nodejs-lockfile-parser copied to clipboard

feat: tree walker

Open milahu opened this issue 2 years ago • 0 comments

every tree needs a tree walker ; )

npm/logical-tree

npm/logical-tree fork

i use this to build a deep node_modules with symlinks, just like pnpm

its useful to have an array of parent nodes in the walker function

sample

  const deptree = await buildDepTree(
    read('package.json'),
    read(lockfilePath),
    false,
    lockfileTypeOfName[path.basename(lockfilePath)],
    true,
  );

  function walk_deptree(_this, enter, _seen, deptreePath = []) {

    // note: this will deduplicate deps
    if (!_seen) { _seen = new Set() }
    if (_seen.has(_this)) { return }
    _seen.add(_this)

    enter(_this, function recurse() {
      for (let key in _this.dependencies) {
        walk_deptree(_this.dependencies[key], enter, _seen, deptreePath.concat([_this]))
      }
    }, deptreePath)
  }

  //deptree.forEach((dep, recurse, deptreePath) => {
  walk_deptree(deptree, function enter(dep, recurse, deptreePath) {
    // enter
    console.log(`${deptreePath.map(_ => `+ `).join('')}${dep.name}@${dep.version}`);
    recurse();
    // leave
  });

milahu avatar Sep 16 '21 18:09 milahu