Skip to content

Instantly share code, notes, and snippets.

@dmitry-vsl
Last active February 20, 2016 19:43
Show Gist options
  • Save dmitry-vsl/1614fc9eaa5d6cd0a42e to your computer and use it in GitHub Desktop.
Save dmitry-vsl/1614fc9eaa5d6cd0a42e to your computer and use it in GitHub Desktop.
fromCallback = (fn) ->
stream = []
cb = ->
for cb in stream
cb.apply @, arguments
fn cb
stream
map = (fn) -> (stream) ->
result = []
stream.push ->
mapped = fn.apply @, arguments
for cb in result
cb mapped
result
filter = (fn) -> (stream) ->
result = []
stream.push ->
if fn.apply @, arguments
for cb in result
cb.apply @, arguments
result
flatMap = (fn) -> (stream) ->
result = []
stream.push ->
newStream = fn.apply @, arguments
newStream.push ->
for cb in result
cb.apply @, arguments
result
subscribe = (fn) -> (stream) ->
stream.push -> fn.apply @, arguments
# TEST
c_ = null
stream = fromCallback (c) -> c_ = c
mapped = map((val) -> val + 'bar')(stream)
filtered = filter((val) -> true)(mapped)
c_2 = null
flatMapped = flatMap(
(val) -> fromCallback (cb) -> c_2 = (a) -> cb val, a
)(filtered)
subscribe(-> console.log.apply(console,arguments))(flatMapped)
c_('foo')
c_2('baz')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment