Skip to content

Instantly share code, notes, and snippets.

@rpominov
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save rpominov/0b9b99f3652cc2cc8062 to your computer and use it in GitHub Desktop.

Select an option

Save rpominov/0b9b99f3652cc2cc8062 to your computer and use it in GitHub Desktop.
lightest streams
function createStream(executor) {
return {
observe(sink) {
return executor(sink)
}
}
}
function map(fn, stream) {
return createStream(sink => {
retrun stream.observe(x => sink(fn(x)))
})
}
function filter(fn, stream) {
return createStream(sink => {
retrun stream.observe(x => {
if (fn(x)) {
sink(x)
}
})
})
}
function flatMap(fn, stream) {
const unobserveCallbacks = []
retrun createStream(sink => {
let unobserve = stream.observe(x => {
let unobserve = fn(x).observe(sink)
unobserveCallbacks.push(unobserve)
})
unobserveCallbacks.push(unobserve)
retrun () => {
unobserveCallbacks.forEach(cb => cb())
}
})
}
// need `of(x)`, for which need completion
@rpominov

Copy link
Copy Markdown
Author

This part

observe(sink) {
  return executor(sink)
}

suggests, that observe is simply = to executor, so a stream basically is executor. Is this the "function class" pattern that was mentioned here and here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment