Last active
August 29, 2015 14:13
-
-
Save doronhorwitz/92739a80337b67071373 to your computer and use it in GitHub Desktop.
lazy variable initialization factory for AngularJS
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
/* | |
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