Forked from WebReflection/String.prototype.template.js
Created
January 6, 2016 10:15
-
-
Save rook2pawn/5c747178d1fab56ee746 to your computer and use it in GitHub Desktop.
ES6 Template like strings in ES3 compatible syntax.
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
// accepts optional transformer | |
// now transformers are compatible with ES6 | |
String.prototype.template = function (fn, object) {'use strict'; | |
// Andrea Giammarchi - WTFPL License | |
var | |
hasTransformer = typeof fn === 'function', | |
stringify = JSON.stringify, | |
re = /\$\{([\S\s]*?)\}/g, | |
strings = [], | |
values = hasTransformer ? [] : strings, | |
i = 0, | |
str, | |
m | |
; | |
while ((m = re.exec(this))) { | |
str = this.slice(i, m.index); | |
if (hasTransformer) { | |
strings.push(str); | |
values.push('(' + m[1] + ')'); | |
} else { | |
strings.push(stringify(str), '(' + m[1] + ')'); | |
} | |
i = re.lastIndex; | |
} | |
str = this.slice(i); | |
strings.push(hasTransformer ? str : stringify(str)); | |
if (hasTransformer) { | |
str = 'function' + (Math.random() * 1e5 | 0); | |
strings = [ | |
str, | |
'with(this)return ' + str + '(' + stringify(strings) + ( | |
values.length ? (',' + values.join(',')) : '' | |
) + ')' | |
]; | |
} else { | |
strings = ['with(this)return ' + strings.join('+')]; | |
} | |
return Function.apply(null, strings).call( | |
hasTransformer ? object : fn, | |
hasTransformer && fn | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment