Problem
Generating an independent to outer variables function, containing data derived during runtime, with a real parse-able function, not a messy unreadable, multiline string.
So, basically, I want to have a real function to be a template, which will during runtime be filled with some data and regenerated.
For example, the following:
var initialFunc = function() {
var someObject = {
prop: valueToReplace
};
return someObject;
};
might later become:
var initialFunc = function() {
var someObject = {
prop: "this was derived during runtime"
};
return someObject;
};
Why
You are probably wondering why not just generate it like that in first place - because the data is gathered during runtime.
Then the options are:
- Concatenate a (sometimes really) big, multiline, messy string;
- This solution.
Solution
Here is how the regeneration process would look like:
var generated = new Function( "(" + function(valueToSwap) {
var someObject = {
prop: valueToSwap
};
return someObject;
} + ")(\"" + value + "\");" );
// the quotes are only necessary for string params of course
What this baby does, is:
- Converts the passed real parsed function to string
- Creates a function wrapping a self execution function and
- The self execution function passes itself the needed parameters
I would recommend on creating a func that generates the parameter list, that is passed, so there are no hardly readable parts of the generation.
That's it.
Comments on HN.