Forked from WebReflection/String.prototype.template.js
Last active
May 31, 2021 14:15
-
-
Save hooblei/bb269de061d111addc9b 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 & me - WTFPL License | |
var | |
hasTransformer = typeof fn === 'function', | |
stringify = JSON.stringify, | |
re = /\$\{/g, | |
strings = [], | |
values = hasTransformer ? [] : strings, | |
i = 0, | |
l = this.length, | |
c, | |
n, | |
str, | |
m | |
; | |
while ((m = re.exec(this))) { | |
str = this.slice(i, m.index) | |
if (str.length) { | |
strings.push(hasTransformer && str || stringify(str)); | |
} | |
n = 1; | |
i = m.index + 2; | |
while (i < l) { | |
c = this[i++]; | |
n += ((c == '{') && 1) || ((c == '}') && -1) || 0; | |
if (!n) { | |
values.push('(' + this.slice(m.index + 2, i - 1) + ')') | |
break; | |
} | |
} | |
} | |
if (i < l) { | |
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 | |
); | |
}; | |
// -- | |
function uc(strings /* ...values */) { | |
return ([].slice.call(arguments, 1)).reduce(function (a, v, i) { | |
a.push(strings[i]); | |
a.push(String(v).toUpperCase()); | |
return a; | |
}, []).join(''); | |
}; | |
function f(_) { return 'foo'; } | |
console.log('${num} is the loneliest number'.template({num: 'One'})); | |
// One is the loneliest number | |
console.log('hm ... ${f({a: {b : 1}})}'.template({f: f, a: 1})); | |
// hm ... foo | |
console.log('hm ... ${f({a: {b : 1}})}'.template(uc, {f: f, a: 1})); | |
// hm ... FOO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment