Skip to content

Instantly share code, notes, and snippets.

@askucher
Last active December 30, 2015 00:39
Show Gist options
  • Save askucher/7751044 to your computer and use it in GitHub Desktop.
Save askucher/7751044 to your computer and use it in GitHub Desktop.
Reactive framework for nodejs. Made for simple things lovers.
const p = require \./reactive.js
######
# Benefits:
# Do not care about when it will be executed
# You can return simple result or promise of result
######
#Simple example:
const chain =
* (input) ->
const promise = p.promise!
# you can create request and put promise.success as callback here.
# The second function will be executed only after data obtained
promise.success do
result-field: input.initial-field
result-field2: 2
promise
* (input) ->
const promise = p.promise!
promise.success do
result: input.result-field + input.result-field2
promise
p.go chain, { initial-field: 1 } #=> {result: 3 }
#Composition:
const composition =
* (input) -> input.initial-field
* (input) -> input + 1
const chain2 =
* composition
* (input) -> input+2
p.go chain2, { initial-field: 1 } #=> 4
#Parallel:
const chain3 =
* task1: (input) -> input.initial-field
task2: (input) -> input.initial-field
* (input) -> input.taks1 + input.taks2
p.go chain3, { initial-field: 1 } #=> 2
const p = require \prelude-ls
class Promise
->
@callbacks= []
success: (result) ->
@callbacks |> p.each (-> it result)
on-success: ->
if @callbacks.length > 0
throw 'Callback is already assigned for ' + @name
@callbacks.push it
class Parallel
(config)->
@tasks = config |> p.obj-to-pairs
@results = []
@callbacks = []
ref = @
@success= (name, res) -->
ref.results.push [name,res]
if ref.tasks.length is ref.results.length
for callback in ref.callbacks
ref.results |> p.pairs-to-obj |> callback
on-success : (func)->
@callbacks.push func
run : (val) ->
for pair in @tasks
const array = pair[1] ++ [ @success pair[0] ]
go array, val
const go = (fns, val) -->
const o = fns.shift!
if !o? then return
const process-val = (nval)->
const next = go fns
if typeof! nval is \Object and typeof! nval.on-success is \Function
nval.on-success next
else
next nval
switch (typeof! o)
case \Function
val |> o |> process-val
case \Array
go (o ++ fns), val
case \Object
const parallel = new Parallel o
parallel.on-success process-val
parallel.run val
module.exports =
promise : -> new Promise!
go: go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment