-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
36 lines (32 loc) · 972 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
35
36
const defaults = {
regex: /{(.*?)}/g,
skipUndefined: false,
spreadToken: '$n',
spreadSeparator: ','
}
function formatMatch(match, attrs, value, options) {
for (let i=0; i<attrs.length; i++) {
let attr = attrs[i]
if (attr === options.spreadToken && Array.isArray(value)) {
return value.map(v => formatMatch(match, attrs.slice(i+1), v, options)).join(options.spreadSeparator)
}
value = value ? value[attr] : undefined
}
if (!value && options.skipUndefined) {
return match
}
else {
return value === undefined ? '' : value
}
}
function format(string, object, options={}) {
if (typeof string !== 'string') {
return string
}
options = { ...defaults, ...options }
return string.replace(options.regex, (...match) => {
let attrs = match[1].split('.')
return formatMatch(match[0], attrs, object, options)
})
}
module.exports = format