Skip to content

Instantly share code, notes, and snippets.

@emattson
Created January 13, 2015 20:11
Show Gist options
  • Save emattson/f3169c725fc105ae74ab to your computer and use it in GitHub Desktop.
Save emattson/f3169c725fc105ae74ab to your computer and use it in GitHub Desktop.
count-identifiers.js es6 version
//depends on shift-parser, shift-reducer, and shift MonoidalReducer
import parse from "shift-parser";
import reduce, {
MonoidalReducer
}
from "shift-reducer";
//IdentifierCounter inherits from MonoidalReducer
class IdentifierCounter extends MonoidalReducer {
//reduce over a shift ast counting the Identifiers
static count(program) {
return reduce(new this, program);
}
//must return a Monoid
constructor() {
super(class Sum {
//by default reduce a 0 for any node
static empty() {
return 0;
}
//override concat to sum nodes
concat(a) {
return this + a;
}
});
}
//only need to override MonoidalReducer for IdentifierExpressions to count number of Identifiers
reduceIdentifierExpression(node, identifier) {
return 1; //will be summed
}
}
//test code
let program = `function f() { hello(world); }`;
console.dir(IdentifierCounter.count(parse(program)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment