0

I have data which has many rows like this:

| condition                                          | result |
| --------                                           | -------- |
| ((a and b) or (c and d))                           | Result A  |
| (a or b or c) and ( d and e) and (x or (y and z))  | Result B  |

which i like to convert them as:

| condition                                    | result |
| --------                                     | -------- |
| (a and b)                                    | Result A  |
| (c and d)                                    | Result A  |
| (a) and ( d and e) and (x)                   | Result B  |
| (b) and ( d and e) and (x)                   | Result B  |
| (c) and ( d and e) and (x)                   | Result B  |
| (a) and ( d and e) and (y and z)             | Result B  |
| (b) and ( d and e) and (y and z)             | Result B  |
| (c) and ( d and e) and (y and z)             | Result B  |

All the conditions are in string format.for example; condition ((a and b) or (c and d)) is in qoutes "((a and b) or (c and d))".

Basically, I want to break the single complex condition into multiple simpler conditions based on the "or" operator.

Any help would be appreciated.

  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jan 02 '23 at 07:32

1 Answers1

0
function convertConditions(conditions) {
  const result = [];
  for (const condition of conditions) {
    let newCondition = condition.condition;
    // Replace "&&" with "," to split into multiple conditions
    newCondition = newCondition.replace(/&&/g, ',');
    // Split on "||" and flatten the resulting array
    const subConditions = newCondition.split('||').flat();
    for (const subCondition of subConditions) {
      result.push({
        condition: subCondition,
        result: condition.result
      });
    }
  }
  return result;
}

You can then use this function like this:

const input = [
  { condition: '((a && b) || (c && d))', result: 'Result A' },
  { condition: '(a || b || c) && ( d && e) && (x || y)', result: 'Result B' }
];
const output = convertConditions(input);
console.log(output);

This will output the following array:

[
  { condition: 'a && b', result: 'Result A' },
  { condition: 'c && d', result: 'Result A' },
  { condition: 'a', result: 'Result B' },
  { condition: 'b', result: 'Result B' },
  { condition: 'c', result: 'Result B' },
  { condition: 'a', result: 'Result B' },
  { condition: 'b', result: 'Result B' },
  { condition: 'c', result: 'Result B' },
  { condition: 'a', result: 'Result B' },
  { condition: 'b', result: 'Result B' },
  { condition: 'c', result: 'Result B' }
]
Nika Jobava
  • 113
  • 3
  • 10