Created
February 3, 2015 23:47
-
-
Save emattson/1eb3233d2db4970d05ee to your computer and use it in GitHub Desktop.
es5 version of count-identifiers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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