Created
July 13, 2015 14:22
-
-
Save dannvix/214bc31ae46d8c447333 to your computer and use it in GitHub Desktop.
Python-like template string in ECMAScript 6
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
// 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