Representing logic as data in JSON

前端 未结 12 1453
眼角桃花
眼角桃花 2021-01-29 21:37

For business reasons we need to externalize some conditional logic into external files: preferably JSON.

A simple filter-by scenario could be handled by adding a node a

12条回答
  •  时光说笑
    2021-01-29 22:19

    I just wanted to help by defining a parsing logic in JavaScript for the JSON structure mentioned in the answer: https://stackoverflow.com/a/53215240/6908656

    This would be helpful for people having a tough time in writing a parsing logic for this.

    evaluateBooleanArray = (arr, evaluated = true) => {
        if (arr.length === 0) return evaluated;
        else if (typeof arr[0] === "object" && !Array.isArray(arr[0])) {
          let newEvaluated = checkForCondition(arr[0]);
          return evaluateBooleanArray(arr.splice(1), newEvaluated);
        } else if (typeof arr[0] === "string" && arr[0].toLowerCase() === "or") {
          return evaluated || evaluateBooleanArray(arr.splice(1), evaluated);
        } else if (typeof arr[0] === "string" && arr[0].toLowerCase() === "and") {
          return evaluated && evaluateBooleanArray(arr.splice(1), evaluated);
        } else if (Array.isArray(arr[0])) {
          let arrToValuate = [].concat(arr[0]);
          return evaluateBooleanArray(
            arr.splice(1),
            evaluateBooleanArray(arrToValuate, evaluated) 
          );
        } else {
          throw new Error("Invalid Expression in Conditions");
        }
      };
    

    So the param arr here would be an array of conditions defined in the format as described by the attached link.

提交回复
热议问题