首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在JavaScript中将动态字符串转换为逻辑表达式

在JavaScript中将动态字符串转换为逻辑表达式
EN

Stack Overflow用户
提问于 2019-05-16 02:39:55
回答 2查看 69关注 0票数 0

这一次可能有点困难,因为除了标准操作符之外,我还没有看到任何人尝试过这一点。

我有一个包含大约50k行对象的表,每一行都需要对它们运行一组表达式“最多30”,并返回true或false。我已经成功地使用了大量的张量操作符,但是它很快就变得凌乱了。

有人有更好的方法吗?下面的最小代码-问题在验证函数中。

代码语言:javascript
复制
const objects = [
    {
        'First Name': 'Chris',
        'Age': 18,
        'Major': 'Mathematics',
        'College Department': 'Mathematics'
    },
    {
        'First Name': 'null',
        'Age': 21,
        'Major': 'Mathematics',
        'College Department': 'Science'
    }
]

const validate = (object, rule) => {
    // logic to convert rule to logical expression
}

const results = objects.map(object => {
    var flags = []
    flags.push(validate(object, '[Fist Name] is null'))
    flags.push(validate(object, '[Age] < [Required Age]'))
    flags.push(validate(object, '[Major] === [College Department] and [Age] > [Required Age]'))  
    // Validate is supposed to return 
    // {Rule: '[Fist Name] is null', Flag: false/true, ...Rest of original object and key pairs} 

    // ... Return array of flags
    return flags;
})

// Result should look like this
// lets say required age is 18
[
    [
        {Rule: '[Fist Name] is null', Flag: false, 'First Name': 'Chris', 'Age': 18, 'Major': 'Mathematics', 'College Department': 'Mathematics'},
        {Rule: '[Age] < [Required Age]', Flag: false, 'First Name': 'Chris', 'Age': 18, 'Major': 'Mathematics', 'College Department': 'Mathematics'},
        {Rule: '[Major] === [College Department] and [Age] > [Required Age]', Flag: true, 'First Name': 'Chris', 'Age': 18, 'Major': 'Mathematics', 'College Department': 'Mathematics'}   
    ],
    [
        {Rule: '[Fist Name] is null', Flag: true, 'First Name': 'null', 'Age': 21, 'Major': 'Mathematics', 'College Department': 'Science'},
        {Rule: '[Age] < [Required Age]', Flag: false, 'First Name': 'null', 'Age': 21, 'Major': 'Mathematics', 'College Department': 'Science'},
        {Rule: '[Major] === [College Department] and [Age] > [Required Age]', Flag: false, 'First Name': 'null', 'Age': 21, 'Major': 'Mathematics', 'College Department': 'Science'}  
    ]
]

// I know how to concat the arrays into one, 
// so either the above output works or the one below works
[
    {Rule: '[Fist Name] is null', Flag: false, 'First Name': 'Chris', 'Age': 18, 'Major': 'Mathematics', 'College Department': 'Mathematics'},
    {Rule: '[Age] < [Required Age]', Flag: false, 'First Name': 'Chris', 'Age': 18, 'Major': 'Mathematics', 'College Department': 'Mathematics'},
    {Rule: '[Major] === [College Department] and [Age] > [Required Age]', Flag: true, 'First Name': 'Chris', 'Age': 18, 'Major': 'Mathematics', 'College Department': 'Mathematics'}, 
    {Rule: '[Fist Name] is null', Flag: true, 'First Name': 'null', 'Age': 21, 'Major': 'Mathematics', 'College Department': 'Science'},
    {Rule: '[Age] < [Required Age]', Flag: false, 'First Name': 'null', 'Age': 21, 'Major': 'Mathematics', 'College Department': 'Science'},
    {Rule: '[Major] === [College Department] and [Age] > [Required Age]', Flag: false, 'First Name': 'null', 'Age': 21, 'Major': 'Mathematics', 'College Department': 'Science'}  
]

Update --这是我已经取得的成就,但只能在>、<=、>或至少到目前为止所测试的所有情况下才能做到。我将添加更多的详细评论很快。

代码语言:javascript
复制
const object = {Age: 10, Required: 18};
const rules = [
    {R: '["Age"] < ["Required"]', O: ['<']},
    {R: '["Age"] <= ["Required"]', O: ['<=']},
    {R: '["Age"] > ["Required"]', O: ['>']},
]

// Prototype that will parse the string
// ... then return the indexes of char
// ... we will use this to insert object name before the char
String.prototype.toIndices = function (d) { return this.split("").reduce((a, e, i) => e === d ? a.concat(i) : a, []) };

String.prototype.splice = function(idx, rem, str) {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};

Object.prototype.validateRule = function (r) {
    const newString = r['R'].toIndices("[").map(s => {
        return r['R'].splice(s, 0, 'object');
    })

    var exp = [];

    for (let item = 0; item < newString.length; item++) {
        for (let obj = 0; obj < newString[item].split(" ").length; obj++) {
            if (newString[item].split(" ")[obj].includes("object"))
                exp.push(newString[item].split(" ")[obj])
        }
    }

    return [...exp].map((e, i) => i < exp.length - 1 ? [e, r['O'][0]] : [e]).reduce((a, b) => a.concat(b)).join(" ");
}


console.log({Rule: rules[0]['R'], Flag: eval(object.validateRule(rules[0]))});
// output
/*
{ Rule: '["Age"] < ["Required"]', Flag: true }
*/

console.log(rules.map(rule => { return {Rule: rule['R'], Flag: eval(object.validateRule(rule))} }));
// output
/*
[ { Rule: '["Age"] < ["Required"]', Flag: true },
  { Rule: '["Age"] <= ["Required"]', Flag: true },
  { Rule: '["Age"] > ["Required"]', Flag: false } ]
*/
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-16 15:35:18

经过几天的创建和修改,我开发了一个将字符串转换为逻辑表达式的解决方案。我用它做了一个包裹:

https://www.npmjs.com/package/validate-table-rules

安装

代码语言:javascript
复制
npm install validate-table-rules

快速入门

代码语言:javascript
复制
'use strict';

//  Required module
const ruleSet = require('validate-table-rules');

// Attach module to Object prototype
Object.prototype.rule = ruleSet.rules;

// Declare and object
const object = [
    {Age: 18, Required: 21}
];

// Sample case -> pass in names you
// want to check for in attached object
console.log(object.rule('[Age] < [Required]')) // output = true
console.log(object.rule('[Age] > [Required]')) // output = false

享受吧!

票数 0
EN

Stack Overflow用户

发布于 2019-05-16 03:21:02

如果您需要计算的表达式提前知道,请用代码写出表达式。

代码语言:javascript
复制
const rules = new Map()
rules.set("[First Name] is null", function(object) {
    return object.firstName === null
})

创建自己的迷你语言是一件很大的工作。如果您需要让用户添加自定义规则,那么构建规则解析器和评估引擎是有意义的。

在解析代码中,计算表达式的方法通常是将输入分解为令牌,然后在第二步中计算这些标记。

代码语言:javascript
复制
function parse(textInput) {
    return arrayOfTokens
}

文本输入示例:[Fist Name] is null

令牌数组示例:[ new Field("First Name"), new OpIsNull() ]

为不同的文本输入编写大量单元测试,并确保它返回预期的标记。当解析工作正常时,下一步是计算令牌。为令牌、对象和预期输出值的数组编写大量单元测试。

代码语言:javascript
复制
function evaluate(object, tokens) {
    let leftHand = null
    if (tokens[0] instanceof Field) {
        leftHand = getFieldValue(object, tokens[0])
    }
    if (tokens[1] instanceof OpIsNull) {
        return leftHand === null
    }
    // etc
}

function getFieldValue(object, field) {
    if (field.name == "First Name") {
        return object.firstName
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56160045

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档