Skip to content

Instantly share code, notes, and snippets.

@emattson
Created February 3, 2015 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emattson/1eb3233d2db4970d05ee to your computer and use it in GitHub Desktop.
Save emattson/1eb3233d2db4970d05ee to your computer and use it in GitHub Desktop.
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