Created
July 16, 2017 13:16
-
-
Save losnir/68a081ecd272a9ee152f698cb32e6774 to your computer and use it in GitHub Desktop.
ES15 String Formatting using Tagged Template Literal
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
function interpolateStringLiteral (template, tokens, input) { | |
const dict = input[input.length - 1] || {}; | |
return template.reduce((accumulator, part, i) => { | |
const key = tokens[i]; | |
const value = Number.isInteger(key) ? input[key] : dict[key]; | |
accumulator.push(part); | |
accumulator.push(value); | |
return accumulator; | |
}, []); | |
} | |
export const format = (template, ...tokens) => (...input) => { | |
return interpolateStringLiteral(template, tokens, input).join(''); | |
} | |
export const jsx = (template, ...tokens) => (...input) => { // eslint-disable-line react/display-name | |
const pieces = interpolateStringLiteral(template, tokens, input); | |
return React.createElement('span', null, ...pieces); | |
} |
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
import React from 'react'; | |
import { format, jsx } from 'formatter'; | |
const template1 = format`Hello, my name is ${0}, and I like playing the ${1}.`; | |
const template2 = jsx`Hello, my name is ${0}, and I like playing the ${1}.`; | |
// String | |
console.log(template1('Nir', 'Drums')); | |
// JSX | |
class Greeting extends React.Component { | |
render () { | |
return template2(<strong>Nir</strong>, <u>Drums</u>); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment