Created
January 15, 2020 15:42
-
-
Save rrichardsonv/82d2a922b5165ca3902bd2fdd7a2913b to your computer and use it in GitHub Desktop.
elixir style stream
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 (collection) { | |
this.collection = collection | |
this.transformations = [] | |
this.acc = [] | |
} | |
run () { | |
let acc = this.acc | |
let i = -1 | |
while (++i < this.collection.length) { | |
let item = this.collection[i] | |
this.transformations.forEach(transformFn => { | |
if (typeof item === 'undefined') return | |
if(transformFn.length == 2) { | |
acc = transformFn(acc, item) | |
} else { | |
item = transformFn(item) | |
} | |
}) | |
} | |
return acc | |
} | |
reduce (reducerFn, acc) { | |
this.transformations.push(reducerFn) | |
this.acc = acc | |
return this | |
} | |
reverse () { | |
this.enum.reverse() | |
return this | |
} | |
map (mapperFn) { | |
this.transformations.push(mapperFn) | |
return this | |
} | |
filter (predicate) { | |
const transform = item => predicate(item) ? item : undefined | |
this.transformations.push(transform) | |
return this | |
} | |
reject (predicate) { | |
const transform = item => predicate(item) ? undefined : item | |
this.transformations.push(transform) | |
return this | |
} | |
} | |
/* | |
To use: | |
s = new Stream ([1,2,3]) | |
s.map((item) => item + 1) | |
.filter((item) => item % 2 === 0) | |
.reduce((agg, item) => agg + item, 0) | |
.run() | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment