Created
June 28, 2017 19:39
-
-
Save nojvek/fb40e4bcbb5e632fb7961a4787360de4 to your computer and use it in GitHub Desktop.
Module loader interview question
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
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