Last active
April 10, 2021 14:14
-
-
Save bryanerayner/68e1498d4b1b09a30ef6 to your computer and use it in GitHub Desktop.
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
/** | |
* Produces a function which uses template strings to do simple interpolation from objects. | |
* | |
* Usage: | |
* var makeMeKing = generateTemplateString('${name} is now the king of ${country}!'); | |
* | |
* console.log(makeMeKing({ name: 'Bryan', country: 'Scotland'})); | |
* // Logs 'Bryan is now the king of Scotland!' | |
*/ | |
var generateTemplateString = (function(){ | |
var cache = {}; | |
function generateTemplate(template){ | |
var fn = cache[template]; | |
if (!fn){ | |
// Replace ${expressions} (etc) with ${map.expressions}. | |
var sanitized = template | |
.replace(/\$\{([\s]*[^;\s\{]+[\s]*)\}/g, function(_, match){ | |
return `\$\{map.${match.trim()}\}`; | |
}) | |
// Afterwards, replace anything that's not ${map.expressions}' (etc) with a blank string. | |
.replace(/(\$\{(?!map\.)[^}]+\})/g, ''); | |
fn = Function('map', `return \`${sanitized}\``); | |
} | |
return fn; | |
}; | |
return generateTemplate; | |
})(); |
Hm. And what about: fs.readFile('views/template.somelanguageorhtml','utf-8', function(err, data){
var d= generateTemplateString(data); console.log(d({ name: 'Bryan', country:'Russia'}));
}) ? Can I or somebody else make like this, say, from a read file or from fs.createReadStream?
there is an error in your function :
var test = generateTemplateString('/api/${param1}/${param2}/')
console.log(test({param1: 'bar', param2: 'foo'})) // /api/bar//
Fixed. Thanks for the help.
It seems to me that cache
is being checked, but never assigned to? Perhaps add cache[template] = fn
on line 29.
I've modified your gist to support cache, and rewritten it to an es6 module
. See the performance gain on jsPerf.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A function which converts a regular string to a function, accepting a map of values to interpolate. Allows dynamic template string creation.