Skip to content

Instantly share code, notes, and snippets.

@dannvix
Created July 13, 2015 14:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dannvix/214bc31ae46d8c447333 to your computer and use it in GitHub Desktop.
Save dannvix/214bc31ae46d8c447333 to your computer and use it in GitHub Desktop.
Python-like template string in ECMAScript 6
// Python-like template string in ECMAScript 6 "tagged template"
// inspired from http://stackoverflow.com/a/22619256
function formatter(literals, ...substitutions) {
return {
format: function() {
let out = [], i = 0, k = 0;
for (i,k; i < literals.length; i++) {
out[k++] = literals[i];
out[k++] = Number.isInteger(substitutions[i]) ?
arguments[substitutions[i]] :
arguments[0][substitutions[i]];
}
out[k] = literals[i];
return out.join("");
},
};
};
console.log(formatter`Hello, ${0}. This is a ${1}`.format("world", "test"));
console.log(formatter`Hello, ${"foo"}. This is a ${"bar"}`.format({foo: "world", bar: "test"}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment