Created
May 14, 2012 17:32
-
-
Save jldailey/2695229 to your computer and use it in GitHub Desktop.
The simplest arbitrary dependency system I could make in CoffeeScript (so far).
This file contains hidden or 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
# In other words, load your async scripts in any order; | |
# express their relationships locally with the code. | |
# This is just some hobby code I wrote last night, | |
# I welcome comments on how to make it simpler or better. | |
# Works with any functions: | |
# > depends ["A","B"], provides "C", -> console.log "win!" | |
# > depends "A", -> provide "B" | |
# > provide "A" | |
# > $(document).ready provides "jquery" | |
# > depends "jquery", doSomeStuff | |
{depends, provides, provide} = (-> | |
qu = [] | |
done = {} | |
filt = (n) -> (n.split?(",") or n).filter (i) -> not (i of done) | |
depends = (needs, f) -> | |
if (needs = filt(needs)).length is 0 then f() | |
else qu.push (need) -> | |
((needs.splice i, 1) if ( i = needs.indexOf need ) > -1) and | |
needs.length is 0 and | |
f | |
f | |
provide = (needs) -> | |
for need in filt(needs) | |
done[need] = i = 0 | |
while i < qu.length | |
if (f = qu[i](need)) then (qu.splice i,1; f()) | |
else i++ | |
null | |
provides = (needs, f=->) -> (a...) -> r=f(a...); provide(needs); r | |
depends: depends | |
provide: provide | |
provides: provides | |
)() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment