Created
May 26, 2020 21:08
-
-
Save naturecodevoid/f676061d6b9c99d6380a694da1e75ce9 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
/* A little utility to execute strings as template literals */ | |
// https://gist.github.com/naturecodevoid/d99f217942860dedd25538e7f108f996 | |
const executeTemplateLiteral = (string, args, argNames, replace$ = true) => { | |
let temporary = `${string}`; | |
if (replace$) temporary = temporary.replaceAll("{", "${"); | |
return new Function(...argNames, `return \`${temporary}\`;`)(...args); | |
}; | |
/* And here's an es2015 version: */ | |
// https://gist.github.com/naturecodevoid/d99f217942860dedd25538e7f108f996 | |
// Making a variable outside the strict mode block enables non-strict files to use this code | |
var executeTemplateLiteral = null; | |
// The rest was made by Babel | |
{ | |
"use strict"; | |
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } | |
executeTemplateLiteral = function executeTemplateLiteral(string, args, argNames) { | |
var replace$ = arguments.length <= 3 || arguments[3] === undefined ? true : arguments[3]; | |
var temporary = "" + string; | |
if (replace$) temporary = temporary.replaceAll("{", "${"); | |
return new (Function.prototype.bind.apply(Function, [null].concat(_toConsumableArray(argNames), ["return `" + temporary + "`;"])))().apply(undefined, _toConsumableArray(args)); | |
}; | |
} | |
/* Example: */ | |
const a = 1; | |
console.log(executeTemplateLiteral("{a} test123", [a], ["a"])); | |
// => 1 test123 | |
// You can also: | |
// - use normal template literals | |
// - change the names of variables | |
const b = 2; | |
console.log(executeTemplateLiteral("${a} test123", [b], ["a"], false)); | |
// => 2 test123 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment