1 | import { getValueAtPath } from "./helpers.js"
|
2 |
|
3 | const VALUE = 1
|
4 | const KEY = 2
|
5 | const FUNCTION = 3
|
6 |
|
7 | export const hasMustache = (v) => v.match(/({{[^{}]+}})/)
|
8 |
|
9 | export const getParts = (value) =>
|
10 | value
|
11 | .trim()
|
12 | .split(/({{[^{}]+}})/)
|
13 | .filter((v) => v)
|
14 | .map((value) => {
|
15 | let match = value.match(/{{([^{}]+)}}/)
|
16 |
|
17 | if (!match)
|
18 | return {
|
19 | type: VALUE,
|
20 | value,
|
21 | negated: false,
|
22 | }
|
23 |
|
24 | value = match[1].trim()
|
25 | let negated = value.charAt(0) === "!"
|
26 | if (negated) value = value.slice(1)
|
27 |
|
28 | return {
|
29 | type: KEY,
|
30 | value,
|
31 | negated,
|
32 | }
|
33 | })
|
34 |
|
35 | export const getValueFromParts = (target, parts) => {
|
36 | return parts.reduce((a, part) => {
|
37 | let { type, value, negated } = part
|
38 |
|
39 | let v
|
40 |
|
41 | if (type === VALUE) v = value
|
42 | if (type === KEY) {
|
43 | v = getValueAtPath(value, target)
|
44 | }
|
45 | if (type === FUNCTION) {
|
46 | let args = part.args.map((value) => getValueAtPath(value, target))
|
47 |
|
48 | v = getValueAtPath(part.method, target)?.(...args)
|
49 | }
|
50 |
|
51 | if (negated) v = !v
|
52 |
|
53 | return a || a === 0 ? a + v : v
|
54 | }, "")
|
55 | }
|