highland icon indicating copy to clipboard operation
highland copied to clipboard

Idea for discussion: forkBy

Open mpj opened this issue 9 years ago • 3 comments

I often find myself in the situation where I want to do the inverse of merge, i.e. split the values of a stream into two different streams. I might be missing some obvious functionality, but this is how I do it today - is there a sleeker way?

let forkBy = (strm, evaluator) => {
  let a = _(), b = _()
  _(strm).each(x => evaluator(x) ? a.write(x) : b.write(x))
  return [a, b]
}

Example usage

let isSpecial = str => !!str.match(/^specialcasething/)
let [ specialThings, otherThings ] = forkBy(connectionStream, isSpecial)

Is this a pattern you recognize in your coding?

mpj avatar Aug 30 '15 11:08 mpj

const isSpecial     = str => !!str.match(/^specialcasething/)
const specialThings = connectionStream.fork().filter(str => isSpecial(str))
const otherThings   = connectionStream.fork().filter(str => !isSpecial(str))

ronag avatar Aug 30 '15 12:08 ronag

Is that really the same thing? If I try to replace my code with that all my tests break.

mpj avatar Aug 30 '15 15:08 mpj

In what way do they break? The problem with your implementation is that it isn't lazy and it cannot end...

ronag avatar Aug 30 '15 17:08 ronag