Skip to content

Instantly share code, notes, and snippets.

@jldailey
Created May 14, 2012 17:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jldailey/2695229 to your computer and use it in GitHub Desktop.
Save jldailey/2695229 to your computer and use it in GitHub Desktop.
The simplest arbitrary dependency system I could make in CoffeeScript (so far).
# 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