Created
January 13, 2015 20:11
-
-
Save emattson/f3169c725fc105ae74ab to your computer and use it in GitHub Desktop.
count-identifiers.js es6 version
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
//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