-
-
Save Limitinit/aa4ad36e815bec93a0ad86bb9473c954 to your computer and use it in GitHub Desktop.
Join API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict" | |
api1 = | |
a: (x,y,z,cb) -> setTimeout cb.bind(null, null, x+y+z+1), 500 | |
b: (x,y,z,cb) -> setTimeout cb.bind(null, null, x+y+z+2), 500 | |
api2 = | |
b: (x,y,z,cb) -> setTimeout cb.bind(null, null, x+y+z+3), 500 | |
c: (x,y,z,cb) -> setTimeout cb.bind(null, null, x+y+z+4), 500 | |
join = -> | |
newapi = {} | |
for api in arguments | |
for key, val of api | |
#already exists | |
if newapi[key] | |
newapi[key].fns.push val | |
continue | |
#close around key and api, then init | |
((key, api) -> | |
newapi[key] = -> | |
args = Array::slice.call arguments | |
callback = args.pop() | |
asyncs = [] | |
for fn in newapi[key].fns | |
asyncs.push async.apply.apply null, [fn].concat args | |
async.parallel asyncs, callback | |
null | |
newapi[key].fns = [val] | |
)(key,api) | |
newapi | |
all = join(api1, api2) | |
all.a 3,3,3,(err, results) -> | |
results | |
# [ 11, 12 ] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
api1 = | |
a: -> 1 | |
b: -> 2 | |
api2 = | |
b: -> 3 | |
c: -> 4 | |
join = -> | |
result = {} | |
for api in arguments | |
for key, val of api | |
#already exists | |
if result[key] | |
result[key].fns.push val | |
continue | |
#close around key and api, then init | |
((key, api) -> | |
result[key] = -> | |
rets = [] | |
for fn in result[key].fns | |
rets.push fn.apply null, arguments | |
rets | |
result[key].fns = [val] | |
)(key,api) | |
result | |
joint = join(api1, api2) | |
json joint.b() # [2,3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment