Closed cprecioso closed 6 years ago
A simple implementation (the one I'm using in my projects) would be:
function reduce<T, U>(
fn: (previousValue: U, currentValue: T) => U,
seed?: U
): (stream$: xs<T>) => Promise<U> {
return stream$ => {
let acc = seed as U
return new Promise((f, r) => {
const subscription = stream$.subscribe({
next(v) {
acc = fn(acc, v)
},
complete() {
subscription.unsubscribe()
f(acc)
},
error(err) {
subscription.unsubscribe()
r(err)
}
})
})
}
}
(Although I'm not sure if the subscription.unsubscribe()
calls are necessary)
The two problems I could see happening:
Property
). However, because it returns a Promise that is only fulfilled when the stream ends, they will quickly realize that they can't be used like that.Promise
polyfills to earlier runtimes. Maybe if the operator is kept in the extra
folder, the polyfill only be a requirement for people who actually want this feature, not for everyone using xs
.Hi @cprecioso ! If you think this is valuable, you can release it as a separate package, see e.g. https://www.npmjs.com/package/xstream-between which I published recently. Otherwise, I think this operator is already (basically) available, because you can do stream.fold(f, seed).last()
and then convert to a promise.
I did publish a package for it! xstream-reduce
. I do plan to publish a few more as well. Thanks for the input.
most
has the concept of areduce
operator, which works mostly as the one in theArray.prototype
. It takes an accumulator function and a seed, and builds up a final value, which is given back as aPromise
that will be fulfilled when the stream ends.While it is a simple implementation to do oneself, I think it's helpful for beginners, in order to realize this kind of thing is doable, solving problems in a straightforward way (at least it has helped me do that). I also think it's friendly enough, since the
reduce
method is present in theArray
prototype and even inlodash
, so it's a concept lots of people will be familiar with; and this operator would have similar semantics.