Skip to content

Instantly share code, notes, and snippets.

@nojvek nojvek/loader.js
Created Jun 28, 2017

Embed
What would you like to do?
Module loader interview question
const _moduleRegistry = {};
// Adds a module to _moduleRegistry
function _addModule(name, deps) {
const module = { name, deps };
module.load = () => {
console.log(`'${name}' loaded`);
return module;
}
_moduleRegistry[name] = module;
}
// Returns promise when module is loaded from network
function _fetchModule(name) {
const module = _moduleRegistry[name];
return new Promise((resolve, reject) => {
if (module) {
setTimeout(() => resolve(module), Math.random() * 1000);
}
else {
reject(new Error(`Module ${name} not found`));
}
})
}
(function _addModules() {
_addModule('app', ['components', 'uilib']);
_addModule('components', ['views', 'services']);
_addModule('uilib', ['react', 'router']);
_addModule('react', []);
_addModule('router', ['react']);
_addModule('models', []);
_addModule('views', ['controllers', 'models']);
_addModule('controllers', ['models']);
_addModule('services', []);
_addModule('tests', ['controllers', 'services']);
console.log(_moduleRegistry);
})();
/******************************************************************************************/
/**
* @param {string} entryModule - Entry module that needs to be loaded
* Every module needs to load its dependencies before module.load() can be called.
* Your task is to complete this method.
* You can assume no cyclic dependencies and every dependency is available
*/
function loadModule(entryModule) {
return _fetchModule(entryModule)
.then(module => module.load())
}
// Load entry module
loadModule(`app`)
.then(module => console.log(`'${module.name}' and all its dependencies are loaded!`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.