Last active
July 4, 2016 03:57
-
-
Save TooTallNate/c2091a9d6b438e40bbbc to your computer and use it in GitHub Desktop.
ES6 String iterator that parses line-by-line off of \n
This file contains 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
'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' | |
// '' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@TooTallNate FYI, I've published a package for that: https://github.com/ngryman/lines-iterator.