Skip to content

Instantly share code, notes, and snippets.

@LachlanArthur
Last active July 25, 2022 19:55
Show Gist options
  • Save LachlanArthur/bb87bcd2c8825dd499cb71a1176a4c26 to your computer and use it in GitHub Desktop.
Save LachlanArthur/bb87bcd2c8825dd499cb71a1176a4c26 to your computer and use it in GitHub Desktop.
Simple sprintf in TypeScript using Tagged Template Literals

JS Sprintf

Simple sprintf in JS using Tagged Template Literals

sprintf`There are ${0} monkeys in the ${1}.`( '10', 'tree' );
// > There are 10 monkeys in the tree.

const linkTemplate = sprintf`<a href="${0}" ${2}>${1}</a>`;
linkTemplate('/contact/', 'Contact Us');
linkTemplate('https://example.com', 'Open Preview', 'target="_blank"');
// Pass the index of the value in the template
sprintf`There are ${0} monkeys in the ${1}.`( '10', 'tree' );
// There are 10 monkeys in the tree.
// The indices can be in any order in the string
sprintf`The ${1} has ${0} monkeys in it.`( '10', 'tree' );
// The tree has 10 monkeys in it.
// Undefined values are blank
sprintf`I have ${0} ${2}.`( '1', 'tree' );
// I have 1 .
// Values can be repeated
sprintf`${0} ${0} ${0} ${0} ${0} ${0} ${0} ${0} ${1}`( 'na', 'batman' );
// na na na na na na na na batman
// Reusing HTML fragments is easy
const detailsTemplate = sprintf`
<details ${2}>
<summary>${0}</summary>
${1}
</details>
`;
const items = [
detailsTemplate('Item 1', '<p>Content for item 1</p>', 'open'),
detailsTemplate('Item 2', '<p>Content for item 2</p>'),
].join('');
/*
<details open>
<summary>Item 1</summary>
<p>Content for item 1</p>
</details>
<details >
<summary>Item 2</summary>
<p>Content for item 2</p>
</details>
*/
export default function sprintf(strings: TemplateStringsArray, ...indices: number[]): (...values: string[]) => string;
export default function sprintf(strings, ...indices) {
return (...values) => strings.reduce((total, part, index) => total + part + (values[indices[index]] || ''), '');
}
export default function sprintf( strings: TemplateStringsArray, ...indices: number[] ) {
return ( ...values: string[] ) =>
strings.reduce( ( total, part, index ) =>
total + part + ( values[ indices[ index ] ] || '' ), ''
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment