Skip to content

Instantly share code, notes, and snippets.

@doronhorwitz
Last active August 29, 2015 14:13
Show Gist options
  • Save doronhorwitz/92739a80337b67071373 to your computer and use it in GitHub Desktop.
Save doronhorwitz/92739a80337b67071373 to your computer and use it in GitHub Desktop.
lazy variable initialization factory for AngularJS
/*
Uses the technique at: http://michaux.ca/articles/lazy-function-definition-pattern
Just declare this factory in your project.
Then to use it, inject it into the controller/directive/service where its required and use it like so:
var myLazyVar = lazyVariable(function(){
//some heavy calculation here
return value;
});
myLazyVar(); //first time does calculation
myLazyVar(); //all successive calls to myLazyVar() will just return the calculated value
*/
.factory('lazyVariable', [function() {
return function lazyVariable(valueGenerationFunc) {
var lazyVariableInner = function() {
var value = valueGenerationFunc.call(null);
lazyVariableInner = function() {
return value;
};
return lazyVariableInner();
};
return function lazyVariableWrapper() {
return lazyVariableInner();
};
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment