Created
March 2, 2017 04:37
-
-
Save ccorcos/f06ba7f6690f0c49056fcf2f43c6ee03 to your computer and use it in GitHub Desktop.
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
class Stream { | |
constructor(iterable, cursor, length) { | |
this.iterable = iterable | |
this.cursor = cursor || 0 | |
this.length = length === undefined | |
? iterable.length - this.cursor | |
: length | |
} | |
// Get the first value from the iterable. | |
head() { | |
if (this.length <= 0) { | |
throw new TypeError('index out of range') | |
} | |
return this.iterable[this.cursor] | |
} | |
// Consume the stream by moving the cursor. | |
move(distance) { | |
return new Stream( | |
this.iterable, | |
this.cursor + distance, | |
this.length - distance | |
) | |
} | |
// Same interface as Array.slice but returns a new Stream | |
slice(start, stop) { | |
if (stop < start) { | |
throw new Error('stop < start') | |
} | |
if (stop && stop > this.length) { | |
throw new TypeError('index out of range') | |
} | |
return new Stream( | |
this.iterable, | |
this.cursor + start, | |
(stop || this.length) - start | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment