Last active
February 4, 2019 12:55
-
-
Save sagirk/e02da23eb885ac412384f1e444ac6814 to your computer and use it in GitHub Desktop.
librarySystem with dependencies
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
// 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