Skip to content

Instantly share code, notes, and snippets.

@michaelficarra
Created August 11, 2015 23:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelficarra/b4d00a68cb679f7f500b to your computer and use it in GitHub Desktop.
Save michaelficarra/b4d00a68cb679f7f500b to your computer and use it in GitHub Desktop.
simple templating system built with ES2015 tagged templates
function escapeUsing(escaper) {
return function(literalParts, ...interpolatedParts) {
let s = literalParts[0];
for (let [interpolatedPart, literalPart] of zip(interpolatedParts, literalParts.slice(1))) {
s += escaper(interpolatedPart) + literalPart;
}
return s;
}
}
function* zipWith(combine, ...generators) {
generators = generators.map(g => g[Symbol.iterator]());
do {
let nexts = generators.map(g => g.next());
if (nexts.some(n => n.done)) break;
yield combine(...nexts.map(n => n.value));
} while(true);
}
function* zip(...generators) {
yield* zipWith(Array.of, ...generators);
}
function hex4(c) {
let hex = c.charCodeAt(0).toString(16);
return `${"0000".slice(hex.length)}${hex}`;
}
export const html = escapeUsing(s => s.replace(/[<>&"'`]/g, match => `&#x${hex4(match)};`));
export const js = escapeUsing(s => s.replace(/<\/script>/g, match => `\\u${hex4(match[0])}${match.slice(1)}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment