Last active
June 5, 2019 22:04
-
-
Save ugitch/2100eb4c309b1d8b2b2dbce089e4210f to your computer and use it in GitHub Desktop.
Library system function for loading libraries which relies on loading dependencies for the library
This file contains hidden or 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
(function(root, undefined) { | |
'use strict'; | |
const libraryStorage = {}; | |
function librarySystem(libraryName, dependencies, callback) { | |
// create library | |
if (arguments.length > 1) { | |
let availableDependencies = []; | |
let missingDependencies = []; | |
if (!Array.isArray(dependencies)) { | |
throw new TypeError(`${dependencies} is not an array.`); | |
} | |
else if (dependencies.length > 0){ | |
// arrange so dependencies are available to callback by their names | |
dependencies.forEach(function(dependency) { | |
if (dependency in libraryStorage) { | |
availableDependencies.push(libraryStorage[dependency]); | |
} | |
else { | |
missingDependencies.push(dependency); | |
} | |
}); | |
} | |
if (dependencies.length === availableDependencies.length) { | |
libraryStorage[libraryName] = callback(...availableDependencies); | |
} | |
else { | |
throw new ReferenceError(`Library not created, lacks ${missingDependencies.length} dependencies: ${missingDependencies.reduce((accum, dep) => | |
(accum + ', ' + dep)) | |
}.`); | |
} | |
// fetch library | |
} else { | |
if (!(libraryName in libraryStorage)) { | |
throw new ReferenceError(`${libraryName} is not defined.`); | |
} | |
return libraryStorage[libraryName]; | |
} | |
} | |
root['librarySystem'] = librarySystem; | |
})(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment