UNPKG

749 BJavaScriptView Raw
1'use strict'
2
3const unescape = {
4 '&': decodeURI,
5 '%': decodeURIComponent
6}
7
8const types = {
9 string: (match, value) => value.replace(/\$(%|&)?(\d+)|\$\$/g, (token, sUnescapeType, sIndex) => {
10 if (!sIndex) {
11 return '$'
12 }
13 const string = match[sIndex] || ''
14 if (sUnescapeType) {
15 return unescape[sUnescapeType](string)
16 }
17 return string
18 }),
19
20 object: (match, object) => {
21 const interpolated = {}
22 Object.keys(object).forEach(key => {
23 interpolated[key] = interpolate(match, object[key])
24 })
25 return interpolated
26 }
27}
28
29function interpolate (match, value) {
30 const byType = types[typeof value]
31 if (byType) {
32 return byType(match, value)
33 }
34 return value
35}
36
37module.exports = interpolate