Skip to content

Instantly share code, notes, and snippets.

@losnir
Created July 16, 2017 13:16
Show Gist options
  • Save losnir/68a081ecd272a9ee152f698cb32e6774 to your computer and use it in GitHub Desktop.
Save losnir/68a081ecd272a9ee152f698cb32e6774 to your computer and use it in GitHub Desktop.
ES15 String Formatting using Tagged Template Literal
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);
}
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