Skip to content

Instantly share code, notes, and snippets.

@sagirk
Last active February 4, 2019 12:55
Show Gist options
  • Save sagirk/e02da23eb885ac412384f1e444ac6814 to your computer and use it in GitHub Desktop.
Save sagirk/e02da23eb885ac412384f1e444ac6814 to your computer and use it in GitHub Desktop.
librarySystem with dependencies
// librarySystem with dependencies
(function () {
var libraryStorage = {};
function librarySystem(libraryName, dependencies, callback) {
// If librarySystem is called in 'create' mode, store the library.
if (arguments.length === 3) {
// If the library has dependencies, fetch the dependencies first and then store the library.
if (dependencies.length > 0) {
var fetchedDependencies = dependencies.map(function (dependencyName) {
return librarySystem(dependencyName);
});
libraryStorage[libraryName] = callback.apply(null, fetchedDependencies);
// If the library has no dependencies, store the library without any additional steps.
} else {
libraryStorage[libraryName] = callback();
}
// If librarySystem is called in 'use' mode, return the library.
} else if (arguments.length === 1) {
return libraryStorage[libraryName];
// If librarySystem is called in neither 'create' nor 'use' mode, throw an error.
} else {
throw new TypeError('Invalid argument(s)');
}
}
window.librarySystem = librarySystem;
})();
// Tests
// Test Suite 1
librarySystem('dependency', [], function() {
return 'loaded dependency';
});
librarySystem('app', ['dependency'], function(dependency) {
return 'app with ' + dependency;
});
librarySystem('app'); // 'app with loaded dependency'
// Test Suite 2
librarySystem('name', [], function() {
return 'Gordon';
});
librarySystem('company', [], function() {
return 'Watch and Code';
});
librarySystem('workBlurb', ['name', 'company'], function(name, company) {
return name + ' works at ' + company;
});
librarySystem('workBlurb'); // 'Gordon works at Watch and Code'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment