Skip to content

Instantly share code, notes, and snippets.

@jclulow
Created November 10, 2011 05:18
Show Gist options
  • Save jclulow/1354181 to your computer and use it in GitHub Desktop.
Save jclulow/1354181 to your computer and use it in GitHub Desktop.
Awk in Javascript?
/*
* map predicate to code...
* /regex/ --> function (groups, next)
* ^ ^ function to call if we should
* | \---skip remaining predicates for this line
* \- e.g. groups[1] is first regex group, etc
*/
function line(predicate, codeblock) {
return ({ predicate: predicate, codeblock: codeblock });
}
function awk(predlist, filelist) {
for (fileno = 0; fileno < filelist; fileno++) {
var lines = /* insert magic to read file
* line-by-line, probably using node-lazy */
lines.foreach(function (line) {
var skip = false;
for (predno = 0; predno < predlist.length; predno++) {
var p = predlist[predno];
if (typeof (p.predicate) == 'regex') {
var m = line.match(p.predicate);
if (m) {
p.codeblock(m, function () { skip = true; });
}
} /* XXX handle more types of predicates here?
* e.g. "function(line) --> boolean" predicate?
*/
if (skip)
break;
}
});
}
}
awk([
line(/(.*): *(.*)/, function(g, next) {
if (g[1] === 'interface')
next(); /* skip lines beginning with "interface:" */
}),
line(/.*/, function(g, next) {
console.log('line did not begin with interface: ... ' + g[0]);
})
], ['/tmp/input.txt']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment