Skip to content

Instantly share code, notes, and snippets.

@Ajnasz
Created June 6, 2011 08:03
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 Ajnasz/1009907 to your computer and use it in GitHub Desktop.
Save Ajnasz/1009907 to your computer and use it in GitHub Desktop.
Recursive require
/* 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