-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
85 lines (66 loc) · 2.29 KB
/
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
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
import math from 'mathjs'
function evaluateCondition(expression, variables) {
const operators = {
'==': (a, b) => a === b,
'!=': (a, b) => a !== b,
'>': (a, b) => a > b,
'>=': (a, b) => a >= b,
'<': (a, b) => a < b,
'<=': (a, b) => a <= b
};
const stack = [];
const tokens = expression.split(/\s+/);
for (const token of tokens) {
if (token in variables) {
stack.push(variables[token]);
} else {
stack.push(token);
}
}
const b = stack.pop();
const token = stack.pop();
const a = stack.pop();
if (!operators[token]) return tokens[0]
const result = operators[token](a, b);
return result
}
function evaluateExpression(expression, variables) {
const scope = Object.assign({}, variables);
// Use mathjs for evaluating mathematical expressions
return math.evaluate(expression, scope);
}
export function parseString(input, variables) {
let output = input.replace(/\$\{(\w+)\}/g, (match, variable) => {
if (variables.hasOwnProperty(variable)) {
return variables[variable];
}
return match;
});
output = output.replace(/\?{(.+?)\s+\?([^:]+?):([^}]+?)\}/g, (match, condition, trueValue, falseValue) => {
const evaluatedCondition = evaluateCondition(condition, variables);
return evaluatedCondition ? trueValue.trim() : falseValue.trim();
});
output = output.replace(/\*\{([^}]+?)\}/g, (match, expression) => {
const evaluatedExpression = evaluateExpression(expression, variables);
return evaluatedExpression;
});
return output;
}
/* Examples
// Example usage
const variables = {
name: 'John',
age: 25,
country: 'USA',
hasLicense: true
};
const inputString = 'My name is ${name}. I am ${age} years old.';
const parsedString = parseString(inputString, variables);
console.log(parsedString); // Output: My name is John. I am 25 years old.
const conditionalString = 'I live in {if country === "USA" ? the United States : another country}.';
const parsedConditionalString = parseString(conditionalString, variables);
console.log(parsedConditionalString); // Output: I live in the United States.
const mathExpression = 'The square of ${age} is {{age ^ 2}}.';
const parsedMathExpression = parseString(mathExpression, variables);
console.log(parsedMathExpression); // Output: The square of 25 is 625.
*/