-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
38 lines (30 loc) · 918 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
37
38
function createColorize(colors = {}) {
let MARKS = Object.keys(colors).toString().replace(/,/g, '|')
let RE_BLOCK = new RegExp(
`\\{((?:${MARKS})(?:\\.(?:${MARKS}))*?)\\s|(\\})|(.[^{}]*)`,
'gi'
)
return (input, ...args) => {
input = input.reduce((a, s, i) => (a += args[--i] + s))
let stack = [{ raw: '' }]
input.replace(RE_BLOCK, (block, open, close, other = '', pos) => {
if (open) {
other = block
if (input.indexOf('}', pos) + 1) {
stack.push({ marks: open.split('.').reverse(), raw: '' })
return
}
}
if (close) {
other = block
if (stack.length !== 1) {
let { marks, raw } = stack.pop()
other = marks.reduce((acc, mark) => colors[mark](acc), raw)
}
}
stack[stack.length - 1].raw += other
})
return stack[0].raw
}
}
module.exports = { createColorize }