Skip to content

Instantly share code, notes, and snippets.

@rrichardsonv
Created January 15, 2020 15:42
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 rrichardsonv/82d2a922b5165ca3902bd2fdd7a2913b to your computer and use it in GitHub Desktop.
Save rrichardsonv/82d2a922b5165ca3902bd2fdd7a2913b to your computer and use it in GitHub Desktop.
elixir style stream
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