Created
June 6, 2011 08:03
-
-
Save Ajnasz/1009907 to your computer and use it in GitHub Desktop.
Recursive require
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
/* override require for testing, comment it out */ | |
var require = function (what, cb) { | |
console.log('request: ' + what.join(', ')); | |
setTimeout(function () { | |
require.ready(cb); | |
}, 300); | |
}; | |
require.ready = function (cb) { | |
cb(); | |
}; | |
var recursiveRequire = function (these, callback) { | |
var items = [], cb, i, thl, e; | |
for (i = 0, thl = these.length; i < thl; i += 1) { | |
e = these[i]; | |
if (typeof e === 'string') { | |
items.push(e); | |
} | |
} | |
// lazy isArray | |
// remember, e is the last item of the these array | |
if (typeof e === 'object' && typeof e.length === 'number') { | |
// if last item is an array, call the recursiveRequire function again | |
// and pass that array as the first argument | |
cb = function () { | |
recursiveRequire(e, callback); | |
}; | |
} else { | |
// if e wasn't an array, we reached the last item, so call the callback | |
cb = callback; | |
} | |
require(items, cb); | |
}; | |
/* | |
required modules, | |
if the last item in the array is another array | |
then it will be downlaoded recursively | |
*/ | |
var g = [ | |
'amodule', | |
'bmodule', | |
[ | |
'cmodule', | |
'dmodule', | |
[ | |
'emodule', | |
'fmodule' | |
] | |
] | |
]; | |
// start test | |
recursiveRequire(g, function () { | |
console.log('requested all'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment