-
Notifications
You must be signed in to change notification settings - Fork 2
/
processors.ts
105 lines (90 loc) · 2.29 KB
/
processors.ts
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import parseInterval from 'math-interval-parser';
import Mustache from 'mustache';
/**
* Splits and parses a phrase for mathematical interval expressions.
* @param phrase - Phrase to parse.
* @param count - Target count.
* @returns Phrase.
*/
function parsePluralInterval(phrase: string, count: number) {
const phrases = phrase.split(/\|/);
let returnPhrase = phrase;
// some() breaks on 1st true
phrases.some((p) => {
const [, m1, m2] = p.match(/^\s*([()\[\]\d,]+)?\s*(.*)$/);
// not the same as in combined condition
if (m1) {
if (matchInterval(count, m1)) {
returnPhrase = m2;
return true;
}
} else {
returnPhrase = p;
}
return false;
});
return returnPhrase;
}
/**
* test a number to match mathematical interval expressions
* [0,2] - 0 to 2 (including, matches: 0, 1, 2)
* ]0,3[ - 0 to 3 (excluding, matches: 1, 2)
* [1] - 1 (matches: 1)
* [20,] - all numbers ≥20 (matches: 20, 21, 22, ...)
* [,20] - all numbers ≤20 (matches: 20, 21, 22, ...)
* @param num - Number to match.
* @param interval - Interval query.
* @returns Match or not.
*/
function matchInterval(num: number, interval: string) {
const parsedInterval = parseInterval(interval);
if (parsedInterval && typeof num === 'number') {
const {
from: {
included: fromIncluded,
value: fromValue
},
to: {
included: toIncluded,
value: toValue
}
} = parsedInterval;
if (fromValue === num) {
return fromIncluded;
}
if (toValue === num) {
return toIncluded;
}
return (
Math.min(fromValue, num) === fromValue
&& Math.max(toValue, num) === toValue
);
}
return false;
}
/**
* Handle plural interval templates.
* @param text - Input text.
* @param namedValues - Named values.
* @param values - Listed values.
* @param count - Count.
*/
export function pluralIntervalProcessor(text: string, _, __, count?: number) {
if (/\|/.test(text) && typeof count === 'number') {
return parsePluralInterval(text, count);
}
return text;
}
/**
* Handle mustache templates.
* @param text - Input text.
* @param namedValues - Named values.
* @param values - Listed values.
* @param count - Count.
*/
export function mustacheProcessor(text: string, namedValues: any) {
if (/\{\{.*\}\}/.test(text)) {
return Mustache.render(text, namedValues);
}
return text;
}