Create a gist now

Instantly share code, notes, and snippets.

es5 version of count-identifiers
//es5
var parse = require("shift-parser").default;
var reduce = require("shift-reducer").default;
var MonoidalReducer = require("shift-reducer").MonoidalReducer;
//must return a Monoid
function IdentifierCounter() {
// a monoid over integers and addition
function Sum() {}
// by default reduce any node to the identity, zero
Sum.empty = function() {
return 0;
};
// combine instances by summing their values
Sum.prototype.concat = function(a) {
return this + a;
}
MonoidalReducer.call(this, Sum);
}
IdentifierCounter.prototype = Object.create(MonoidalReducer.prototype);
// a convenience function for performing the reduction and extracting a result
IdentifierCounter.count = function(program) {
return reduce(new this, program);
};
// add 1 to the count for each IdentifierExpression node
IdentifierCounter.prototype.reduceIdentifierExpression = function(node, identifier) {
return 1; //will be summed
}
/*
In this case, the only node we care about overriding is the
IdentifierExpression node; the rest can be reduced using the default
methods from MonoidalReducer.
*/
//test code
var 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