Skip to content

Instantly share code, notes, and snippets.

@ccorcos
Created March 2, 2017 04:37
Show Gist options
  • Save ccorcos/f06ba7f6690f0c49056fcf2f43c6ee03 to your computer and use it in GitHub Desktop.
Save ccorcos/f06ba7f6690f0c49056fcf2f43c6ee03 to your computer and use it in GitHub Desktop.
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