I'm currently facing an issue when trying to compare the array from a JSON file within a TypeScript function. The following code is in index.ts: Remember not to hard-code references to context variables like 'Profession'. Conditions can be nested at various levels. Try converting the condition into postfix-notation for easier evaluation.
import conditionInput from "./condition.json";
/**
* Evaluate a condition against the context.
* @param condition A DSL JSON object.
* @param context An object of key-value pairs
* @return boolean
*/
function evaluate(
condition: typeof conditionInput,
context: { [key: string]: string | undefined }
): boolean {
// Your task is to implement this function to evaluate the imported condition.json with the given context. Variables prefixed with '$' should fetch their values from the context.
// Hint 1: Do not hard-code references to context variables like 'Profession'
// Hint 2: Conditions can be nested, n-levels deep
// Convert the condition into postfix-notation
// Ideally, one value must remain in the result stack with the last operation's result
return false;
}
/**
* Click "run" to execute the test cases, which should pass after your implementation.
*/
(function () {
const cases = [
{
context: {
State: "Alabama",
Profession: "Software development",
},
expected: true,
},
{
context: {
State: "Texas",
},
expected: true,
},
{
context: {
State: "Alabama",
Profession: "Gaming",
},
expected: false,
},
{
context: {
State: "Utah",
},
expected: false,
},
{
context: {
Profession: "Town crier",
},
expected: false,
},
{
context: {
Profession: "Tradesperson",
},
expected: true,
},
];
for (const c of cases) {
const actual = evaluate(conditionInput, c.context);
console.log(actual === c.expected ? "yay :-)" : "nay :-(");
}
})();
The content of condition.json:
[
"OR",
[
"AND",
["==", "$State", "Alabama"],
["==", "$Profession", "Software development"]
],
["AND", ["==", "$State", "Texas"]],
["OR", ["==", "$Profession", "Tradesperson"]]
]