DEV Community

artydev
artydev

Posted on

Combining Streams

What if we wanted to add the values of two streams s1, s2, and react everytime one of the streams is updated ?

Javascript does not allow operations overloading, so we can't just do: s = s1 + s2.

Here is a very simple implementation of a function which combine multiple streams.

function Stream (value) {
  let storedvalue = value
  let mappers = []
  function stream (newvalue) {
    if (arguments.length) {
      mappers.map(f => f(newvalue))
      storedvalue = newvalue
    }
    return storedvalue
  }
  stream.map = function (f) {
    mappers.push(f)
  }
  return stream
}

function combine (f, streams) {
  let s = Stream(0)
  function update (v) {
   let acc = s()
   s(f.apply(null, [acc, v]))
  }
  streams.forEach( st => st.map(update))
  return s
}

s1 = Stream()
s2 = Stream()
s3 = Stream()

let c = combine((x, y) => x + y, [s1, s2, s3])

c.map(v => result.innerHTML = `Result of combination : ${v}`)

s1(3)
s1(3)
s2(5)
s3(56)

You can test it here : combine

Discussion (0)