递归函数来格式化嵌套数组以与条件数组匹配 [英] Recursive function to format nested arrays to match against arrays of conditions
本文介绍了递归函数来格式化嵌套数组以与条件数组匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试编写此eval函数,该函数在某些情况下会循环调用它们,并需要检查它是否与条件数组中的条件匹配并返回true或false。我不确定如何最好地格式化条件数组并对其进行匹配。条件是嵌套的,深度为n级,因此尝试获取递归函数。
Trying to write this eval function that takes in cases, loops through them and needs to check if it matches to a condition in a conditions array and returns true or false. I'm not sure how best to format the conditions array and run the matching on it. Conditions are nested, n-levels deep, so trying to get a recursive function.
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
},
]
推荐答案
您可以采用不带 eval
的方法,并使用数据来构建表达式,并使用一个函数对等价的量化器和一些量化器进行检查,并对 AND
和 OR
。
You could take an approach without eval
and use the data to build expressions with a function for checking with equal and some quantizers for AND
and OR
.
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);
这篇关于递归函数来格式化嵌套数组以与条件数组匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文