Created
January 19, 2016 01:16
-
-
Save stormoz/6ae796c40d068725544e to your computer and use it in GitHub Desktop.
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
var Lazy = function (getFunc) { | |
var _value; | |
return { | |
get value() { | |
if(!_value){ | |
_value = getFunc(); | |
} | |
return _value; | |
} | |
}; | |
}; | |
var lazy = new Lazy(function(){ | |
console.log('get func called'); | |
return 1; | |
}); | |
console.log(lazy.value); // function will be called just once | |
console.log(lazy.value); | |
var lazyRequire = function (modules) { | |
var lazy = {}, | |
propertyName; | |
for(var i = 0; i < modules.length; i++) { | |
propertyName = getPropertyName(modules[i]); | |
Object.defineProperty(lazy, propertyName, { | |
get: getRequireFunc(modules[i]) | |
}); | |
} | |
return lazy; | |
function getRequireFunc(moduleName) { | |
return function(){ | |
return require(moduleName); | |
} | |
} | |
function getPropertyName(moduleName){ | |
var propertyName = "", | |
metDash = false; | |
for(var i = 0; i < moduleName.length; i++) { | |
if(moduleName[i] === '-') { | |
metDash = true; | |
continue; | |
} | |
propertyName += metDash ? moduleName[i].toUpperCase() : moduleName[i]; | |
metDash = false; | |
} | |
return propertyName; | |
} | |
}; | |
var packages = new lazyRequire(['fs', 'gulp-uglify']); | |
console.log(packages.fs.F_OK); // require for 'fs' module will be called here | |
console.log(packages.gulpUglify); // require for 'gulp-uglify' module will be called here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment