Skip to content

Instantly share code, notes, and snippets.

@charleshimmer
Created January 25, 2012 04:14
Show Gist options
  • Save charleshimmer/1674669 to your computer and use it in GitHub Desktop.
Save charleshimmer/1674669 to your computer and use it in GitHub Desktop.
One time computation
function getQueryParams(param) {
var qs = document.location.search.split("+").join(" "),
params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
// redefine this function with a closure around the computed params
getQueryParams = function(param){
return params[param];
};
return params[param];
}
// one time computation / init pattern
function myFunc(arg){
var obj = {};
/*
insert one time computation
*/
// redefine myFunc with closure around arg and obj
myFunc = function(arg){
return obj[arg];
}
}
// can then be used like this
myFunc('arg1'); // runs one time computation block
myFunc('arg2'); // should not run one time comptutation block but still return a result
@charleshimmer
Copy link
Author

Is this the best to have a helper function run some one time computation? Basically it runs some setup and then redefines itself with a closure around the computer variables.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment