Open ash0080 opened 5 years ago
The thing I usually do is write a reducer to give me a map from nodes to their parents:
const { reduce, adapt, MonoidalReducer } = require('shift-reducer');
const parentsMonoid = {
empty() {
return {
children: [],
pairs: [],
};
},
concat(other) {
return {
children: this.children.concat(other.children),
pairs: this.pairs.concat(other.pairs),
};
},
};
const parentsReducer = adapt(
(d, n) => ({
children: [n],
pairs: d.children.map(c => [c, n]).concat(d.pairs),
}),
new MonoidalReducer(parentsMonoid)
);
const parentMap = tree => new Map(reduce(parentsReducer, tree).pairs);
which you can use for this:
const parents = parentMap(tree)
[...]
console.log(locations.get(parents.get(scopeVariables[0].declarations[0].node)))
Many thanks, using a reducer run much faster than before.
Sure, I can traverse AST and check if a FunctionDeclaration 'contains' the BindingIdentifier but, is it the correct usage? Any tips here?