Forked from bryanerayner/generateTemplateString.js
Created
December 17, 2018 19:49
-
-
Save mardix/ad66c7a22174f9164467f86763114486 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; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment