Created
August 11, 2015 23:54
-
-
Save michaelficarra/b4d00a68cb679f7f500b to your computer and use it in GitHub Desktop.
simple templating system built with ES2015 tagged templates
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 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