Skip to content

Instantly share code, notes, and snippets.

@TooTallNate
Last active July 4, 2016 03:57
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 TooTallNate/c2091a9d6b438e40bbbc to your computer and use it in GitHub Desktop.
Save TooTallNate/c2091a9d6b438e40bbbc to your computer and use it in GitHub Desktop.
ES6 String iterator that parses line-by-line off of \n
'use strict';
function *LineIterator (str) {
let pos = 0;
let delimiter = '\n';
while (true) {
let index = str.indexOf(delimiter, pos);
if (index === -1) break;
yield str.substring(pos, index);
pos = index + delimiter.length;
}
yield str.substring(pos);
}
module.exports = LineIterator;
// USAGE /////////////////////////////////////////
for (let line of LineIterator('1\n2\n3\n')) {
console.log(line);
// '1'
// '2'
// '3'
// ''
}
@ngryman
Copy link

ngryman commented Jul 4, 2016

@TooTallNate FYI, I've published a package for that: https://github.com/ngryman/lines-iterator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment