UNPKG

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