Created
September 27, 2015 15:36
-
-
Save blixt/498cac8edcb77db3a701 to your computer and use it in GitHub Desktop.
Formatting templating strings in ES6
This file contains hidden or 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
function format(strings, ...values) { | |
const pieces = []; | |
for (let [index, string] of strings.entries()) { | |
let value = values[index]; | |
const formatIndex = string.lastIndexOf('$'); | |
if (formatIndex != -1) { | |
const format = string.substr(formatIndex + 1); | |
string = string.substr(0, formatIndex); | |
// TODO: Use an actual format engine here. | |
switch (format) { | |
case '02d': | |
if (value < 10) value = '0' + value; | |
break; | |
case 'json': | |
value = JSON.stringify(value); | |
break; | |
} | |
} | |
pieces.push(string); | |
if (value !== undefined) pieces.push(value); | |
} | |
return pieces.join(''); | |
} | |
const person = {name: 'Lisa', occupation: 'Engineer'}; | |
console.log(format`${person.name}'s information: $json${person}`); | |
// -> Lisa's information: {"name":"Lisa","occupation":"Engineer"} | |
const minutes = 3, seconds = 47; | |
console.log(format`The eggs will be ready in $02d${minutes}:$02d${seconds}.`); | |
// -> The eggs will be ready in 03:47. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment