Skip to content

Instantly share code, notes, and snippets.

@donli1210
Created December 4, 2017 21:03
Show Gist options
  • Save donli1210/d1a90664b101e19e2e3fc82b35b81d53 to your computer and use it in GitHub Desktop.
Save donli1210/d1a90664b101e19e2e3fc82b35b81d53 to your computer and use it in GitHub Desktop.
Beasts Question No. 3
// Beasts Question No. 3
// librarySystem with dependencies
// https://github.com/gordonmzhu/beasts/issues/1
(function() {
var libraryStorage = {};
function librarySystem(libraryName, dependencyArray, callback) {
// create object
if (arguments.length > 1) {
// There are dependencies
if (dependencyArray.length > 0) {
var dependencyObjArray = dependencyArray.map(function(dependency) {
return libraryStorage[dependency];
});
//debugger;
libraryStorage[libraryName] = callback.apply(null, dependencyObjArray);
} else {
//No dependency, just create the object
libraryStorage[libraryName] = callback();
}
} else {
return libraryStorage[libraryName];
}
}
window.librarySystem = librarySystem;
})();
tests({
'No dependency': function() {
librarySystem('dependency', [], function() {
return 'loaded dependency';
})
eq("loaded dependency", librarySystem('dependency'));
},
'One dependency': function() {
librarySystem('dependency', [], function() {
return 'loaded dependency';
});
librarySystem('app', ['dependency'], function(dependency) {
return 'app with ' + dependency;
});
eq("app with loaded dependency", librarySystem('app'));
},
'Two dependency': function() {
librarySystem('name', [], function() {
return 'Gordon';
});
librarySystem('company', [], function() {
return 'Watch and Code';
});
librarySystem('workBlurb', ['name', 'company'], function(name, company) {
return name + ' works at ' + company;
});
eq("Gordon works at Watch and Code", librarySystem('workBlurb'));
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment