Created
April 13, 2016 02:16
-
-
Save wilburhimself/bbc4febc052a2e43e7b97e923ce2ad05 to your computer and use it in GitHub Desktop.
Template constructor function
This file contains hidden or 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
| function template(string, options) { | |
| var delimeters = { | |
| open: "*(", | |
| close: ")*" | |
| }; | |
| var templateString = []; | |
| var i = 1; | |
| var closingDelimterLocation = 0; | |
| var functionArguments = []; | |
| var theVariable, remaining; | |
| var wrapInQuotes = function(text) { | |
| return "'" + text + "'"; | |
| } | |
| for (var key in options) { | |
| if (options.hasOwnProperty(key)) { | |
| if (options[key] === undefined) { | |
| delimeters[key] = options[key]; | |
| } | |
| } | |
| } | |
| var segments = string.split(delimeters.open); | |
| var numOfSegments = segments.length; | |
| templateString.push(wrapInQuotes(segments[0])); | |
| while (i < numOfSegments) { | |
| closingDelimterLocation = segments[i].indexOf(delimeters.close); | |
| theVariable = segments[i].slice(0, closingDelimterLocation); | |
| functionArguments.push(theVariable); | |
| templateString.push(theVariable); | |
| remaining = segments[i].slice(closingDelimterLocation + delimeters.close.length); | |
| templateString.push(wrapInQuotes(remaining)); | |
| i++; | |
| } | |
| templateString = 'while(times --) { console.log(' + templateString.join('+') + ')}'; | |
| return new Function(functionArguments.join(','), 'times', templateString); | |
| } | |
| var t = template("Hello *(name)*, what are you *(verb)*"); | |
| t("Wilbur", "eating", 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment