document `this.traverse` vs `this.visit`
- Dominant language
- TypeScript
- Stars
- 1.2k
- Forks
- 194
- Avg merge
- 22h 43m
- Merged PRs (30d)
- 10
Description
**update**: now that my original question has been answered, This issue is now a request for documentation. Leaving it open because the discussion below is a good starting point for a PR.
## Original Post
First a simple explanation of my goal and what I tried
``` js
var inputCode = 'if (DEV_ENV) a(); else b();';
assert.equal(transform(inputCode, true), 'a();');
assert.equal(transform(inputCode, false), 'b();');
function transform(code, DEV_ENV) {
var ast = recast.parse(code);
ast = types.visit(ast, {
visitIfStatement: function(path) {
// traverse 'test' child node *before* evaluating this node
// other transforms may reduce this to a literal value
var test = this.visit(path.get('test'));
// visitIdentifier never gets called if I use this.traverse
// var test = this.traverse(path.get('test'));
var alternate = path.get('alternate');
var consequent = path.get('consequent');
if (n.Literal.check(test)) {
// naive implementation - actual code handles BlockStatements
path.replace(this.traverse(test.value ? consequent : alternate));
} else {
this.traverse(consequent);
this.traverse(alternate);
}
},
visitIdentifier: function(path) {
if (path.value.name === 'DEV_ENV') {
path.replace(b.literal());
}
return false;
},
//...
});
return recast.print(ast).code;
}
```
See the comments about using `this.traverse(path.get('test'));`. What is the difference between the `this.traverse` and `this.visit`? When is it appropriate to use one over the other?
Contributor guide
No contributing guide indexed for this repository
Research direction
Start with the issue's visitIfStatement example and the entry points types.visit, this.visit, and this.traverse, then compare how the example uses each operation on path.get('test'). Document the distinction and when each is appropriate, using the visitIdentifier example as context; the work is done when a reader can choose between them without relying on the original discussion.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100