【问题标题】:Logical operators from Array[object..]来自 Array[object..] 的逻辑运算符
【发布时间】:2021-12-27 10:57:42
【问题描述】:

我目前正在使用类似此代码的布尔和逻辑运算符

仅供参考,我想将数组中的 object.Value 、 object.Logic 转换为逻辑运算符。示例:object1.logic object.operators object2.logic 为真或假

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


我希望结果与

 true || false && true

有人对这个问题有想法吗?

【问题讨论】:

  • 我认为问题需要更多的解释你想要达到的目标。
  • @vaira 我想将数组中的 object.Value 、 object.Logic 转换为逻辑运算符。示例:object1.logic object.operators object2.logic 为真或假

标签: typescript logic logical-operators


【解决方案1】:

您只需要运行reduce 运算符并返回一个新的运算符对象,该对象将具有先前运算符和值或当前计算的逻辑。

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);

如果您想控制操作顺序:

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);

【讨论】:

  • 感谢您的回答,但请问这会导致逻辑问题的优先级吗?例如,我们必须在 || 之前完成 &&
  • 你是说只有两个操作是 && 和 || ,这里你希望 && 应该在 || 之前处理,对吧?
  • @varia 是的
  • @RungkritTitachotnimit 已更新
猜你喜欢
  • 2020-12-20
  • 1970-01-01
  • 1970-01-01
  • 2017-09-08
  • 2011-09-23
  • 2011-08-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多