-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
34 lines (33 loc) · 943 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* eslint-disable no-new-func */
/**
* Interpolate a tagged template literal from the inputs
*
* @param {*} template the template literal string
* @param {*} [tags] the tagged values in the template
* @returns the template output with the tagged literals applied
*/
export function interpolate (template, tags = {}) {
const keys = Object.keys(tags)
const values = Object.values(tags)
try {
return new Function(...keys, `return \`${template}\`;`)(...values)
} catch (e) {
throw new TemplateException(template, tags, e)
}
}
/**
* @private
*/
class TemplateException extends Error {
constructor (template, tags, message) {
super()
this.name = 'TemplateError'
let msg = '\n------------------\n'
msg += `Template: \`${template}\``
msg += '\n------------------\n'
msg += `Tags: ${JSON.stringify(tags, null, 2)}`
msg += '\n------------------\n'
msg += message
this.message = msg
}
}