Skip to content

Instantly share code, notes, and snippets.

@jpedrosa
Created April 12, 2009 06:26
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 jpedrosa/93891 to your computer and use it in GitHub Desktop.
Save jpedrosa/93891 to your computer and use it in GitHub Desktop.
function readLines(file_path,fn){
var px=system.posix,
fd, s, i, len,
NL='\n',
ES="",
BS=8096,
unused=[],
trail_nl,
lines,
last_i;
fd = px.fopen(file_path,"r");
try{
while((s=px.fread(1,BS,fd)).length>0){
trail_nl=s.charAt(s.length-1)==NL;
lines=s.split(NL);
if(trail_nl){
//when splitting with a trailing newline an "extra line" is added so discard it
lines.pop();
}
len=lines.length;
if(len==1&&!trail_nl){
unused.push(lines[0]);
}else{
last_i=len-1;
if(unused.length>0){
lines[0]=unused.join(ES)+lines[0];
unused=[];
}
for(i=0;i<len;i++){
if(i<last_i||trail_nl){
fn(lines[i]);
}else{
unused.push(lines[i]);
}
}
}
}
if(unused.length>0){
fn(unused.join(ES));
}
}finally{
px.fclose(fd);
}
}
var total=0,space=' ';
readLines("/dev/stdin",
function(line){
var a=line.split(space), i, len;
for(i=0,len=a.length;i<len;i++){
total+=(parseInt(a[i],10));
}
});
print(total);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment