staltz / xstream

An extremely intuitive, small, and fast functional reactive stream library for JavaScript
http://staltz.github.io/xstream/
MIT License
2.38k stars 136 forks source link

reduce operator #255

Closed cprecioso closed 6 years ago

cprecioso commented 6 years ago

most has the concept of a reduce operator, which works mostly as the one in the Array.prototype. It takes an accumulator function and a seed, and builds up a final value, which is given back as a Promise 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 the Array prototype and even in lodash, so it's a concept lots of people will be familiar with; and this operator would have similar semantics.

cprecioso commented 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)

cprecioso commented 6 years ago

The two problems I could see happening:

staltz commented 6 years ago

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.

cprecioso commented 6 years ago

I did publish a package for it! xstream-reduce. I do plan to publish a few more as well. Thanks for the input.