Search code examples
typescriptlogiclogical-operators

Logical operators from Array[object..]


i'm currently work with Boolean And logical operators like this code

FYI i want to convert object.Value , object.Logic in array to do Logical operator. Example : object1.logic object.operators object2.logic as true or false

const input: Array<any> = [
    {
        type: "basic",
        value: true,
        logic: "or"
    },
    {
        type: "basic",
        value: false,
        logic: "and"
    },
    {
        type: "basic",
        value: true,
        logic: "and"
    },


i want expect result same as

 true || false && true

Anyone got an idea for this problem ?


Solution

  • You just need to run reduce operator and return a new operator object that will have the logic of previous operator and value or current computation.

    let input = [{
        type: "basic",
        value: true,
        logic: "or"
      },
      {
        type: "basic",
        value: false,
        logic: "and"
      },
      {
        type: "basic",
        value: true,
        logic: "and"
      }
    ]
    
    // if type does not matter 
    
    let result = input.reduce((op1, op2) => ({
      logic: op2.logic,
      value: op1.logic === 'or' ? op1.value || op2.value : op1.value && op2.value
    }));
    // if you have more than ||- && operations you can create function with switch case and call it here.
    
    console.log(result);

    If you want to have control on operation sequence:

    let input = [{
        type: "basic",
        value: true,
        logic: "or"
      },
      {
        type: "basic",
        value: false,
        logic: "and"
      },
      {
        type: "basic",
        value: true,
        logic: "and"
      }
    ]
    
    // logic: and - or
    // operation: (boolean, boolean) =>  boolean; 
    let processOperation = (logic, operation, arr, op) => {
      // if emplty return first
      if (!arr.length) return [op];
    
      let prevOp = arr[arr.length - 1];
    
      if (prevOp.logic === logic) {
        // remove prevous and replace with operation result
        arr.pop()
        arr.push({
          logic: op.logic,
          value: operation(prevOp.value, op.value)
        });
      } else {
        arr.push(op); // if operation logic not matched push it in for future processing
      }
      return arr;
    }
    
    
    
    let result = input
      .reduce(processOperation.bind(this, 'and', (a, b) => a && b), [])
      .reduce(processOperation.bind(this, 'or', (a, b) => a || b), []);
    // here you are deciding the order by the squence in the chiain
    
    // result[0].value will be the solution
    console.log('answer', result);