【问题标题】:Recursive function to format nested arrays to match against arrays of conditions用于格式化嵌套数组以匹配条件数组的递归函数
【发布时间】:2020-05-07 17:35:06
【问题描述】:

尝试编写这个 eval 函数,该函数接收 case,循环遍历它们,并需要检查它是否与条件数组中的条件匹配并返回 true 或 false。我不确定如何最好地格式化条件数组并在其上运行匹配。条件是嵌套的,n 级深,因此试图获得一个递归函数。

console.log(cases.forEach(c => eval(formattedCondition, c.item)))

const conditions = [
 "OR",
 ["AND",["==","maker","airbus"],["==","name","A320"]],
 ["AND",[ "==", "maker","boeing"]],
 ["OR",["==","name","B767"]]
]

const cases = [
 {
   "item": {
    'maker': 'airbus',
    'name':"A320",
   }
 // should return true for this case
 },
 {
   "item": {
    'maker': 'embraer',
    'name':"e175",
   }
 // should return false for this case
 },
 {
   "item": {
    'maker': 'boeing',
   }
 // should return true for this case
 },
 {
   "item": {
    'name':"B767",
   }
// should return true for this case
 },
 {
   "item": {
    'maker': 'boeing',
    'name':"B777",
   }
 // should return false for this case
 },
]

【问题讨论】:

  • 您能否在问题中包含您的实现/尝试制作该功能?
  • 就是这样,我不确定如何格式化会影响搜索结果的条件数组
  • 你能在javascript中插入想要的条件吗?
  • 喜欢orand?是的,为什么不呢。
  • 为什么'name':"B767"的项目要返回false?它与第三个子句匹配,这就足够了。为什么最后一种情况应该返回假?中间子句接受任何波音,对名称没有任何条件,所以它应该返回 true,不是吗?

标签: javascript arrays json object


【解决方案1】:

您可以采用不使用eval 的方法,并使用数据构建表达式,其中包含用于检查相等的函数以及ANDOR 的一些量化器。

const
    conditions = ["OR", ["AND", ["==", "maker", "airbus"], ["==", "name", "A320"]], ["AND", ["==", "maker", "boeing"]], ["OR", ["==", "name", "B767"]]],
    take = object => {
        const
            quantifiers = { AND: 'every', OR: 'some' },
            operators = { '==': (a, b) => a == b },
            evaluate = ([symbol, ...values]) => values.every(v => typeof v === 'string')
                ? operators[symbol](object[values[0]], values[1])
                : values[quantifiers[symbol]](evaluate);
        return evaluate;
    },
    cases = [
        { item: { maker: 'airbus', name: "A320" } },    // true
        { item: { maker: 'embraer', name: "e175" } },   // false
        { item: { maker: 'boeing' } },                  // true
        { item: { name: "B767" } },                     // true
        { item: { maker: 'boeing', name: "B777" } },    // true instead of false
    ],
    result = cases.map(({ item }) => take(item)(conditions));

console.log(result);

【讨论】:

    猜你喜欢
    • 2018-09-23
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 2010-12-18
    相关资源
    最近更新 更多