Javascript 动态计算用户添加的If语句

Javascript 动态计算用户添加的If语句,javascript,swift,Javascript,Swift,如何实现用户可以添加多个自定义if语句 例如,假设有一个名为x的给定变量,其给定值为8。 用户看到x=8,并有一个按钮来添加if语句。他点击按钮,可以插入触发事件的条件(假设它打印“Hello World”)。因此,他将“xBool{ 乐山op酒店{ 如果!(xop){ 返回错误 } } 返回真值 } } 测试: func feasibleHelloWorld(x: MyConditions) { if x.checkConstraints() { print("Hel

如何实现用户可以添加多个自定义if语句

例如,假设有一个名为x的给定变量,其给定值为8。 用户看到x=8,并有一个按钮来添加if语句。他点击按钮,可以插入触发事件的条件(假设它打印“Hello World”)。因此,他将“x<100”输入到字段中,这是真的。因此,“Hello World”被打印出来。 再次单击按钮后,他可以添加其他条件,例如“x<7”,这也是正确的。因为这两个条件都是正确的,“Hello World”仍然打印。 我想你明白我问题的重点了,尽管我缺乏词汇。 那个么,我怎样才能让用户添加一个未定义数量的条件,在打印“Hello World”之前检查这些条件? 我知道的唯一解决办法是限制可能的条件数量,并检查每个条件是否为空/条件说明了什么


非常感谢

首先,您需要一种在运算符之间切换的方法。一个非常简单的
enum
非常适合于此。只需添加所有要使用的运算符

enum Operator : String {

    case biggerThan = ">"
    case smallerThan = "<"
    case equal = "=="

    init?(string:String) {
        switch string {
        case ">" :
            self = .biggerThan
        case "<" :
            self = .smallerThan
        case "==" :
            self = .equal
        default :
            return nil
        }
    }
}
此函数根据
x
inputValue
和所选的
运算符
返回一个
Bool

func checkCondition(x: Int, condition: Condition) -> Bool {
    switch condition.operation {
    case .biggerThan :
        return condition.value > x
    case .smallerThan :
        return condition.value < x
    case .equal :
        return condition.value == x
    }
}
现在,您只需在用户创建条件时将其存储在数组中

func userCondition(operation:String, input:String) -> Condition? {

    guard let op = Operator(string: operation) else {
        return nil
    }
    guard let doubleValue = Double(input) else {
        return nil
    }

    return Condition(value: Int(doubleValue), operation: op)
}

let conditionA = userCondition("<", input: "10")! // use if let instead of !
let conditionB = userCondition(">", input: "10")! // use if let instead of !
let conditionC = userCondition("==", input: "23")! // use if let instead of !

var x : Int = 23

checkAllConditions(x, conditions: [conditionA,conditionB,conditionC])
func用户条件(操作:字符串,输入:字符串)->条件?{
guard let op=操作员(字符串:操作)else{
归零
}
保护let doubleValue=双(输入)else{
归零
}
返回条件(值:Int(doubleValue),操作:op)
}
让条件a=userCondition(“,输入:“10”)!//使用if let代替!
让条件c=userCondition(“==”,输入:“23”)!//使用if let代替!
变量x:Int=23
checkAllConditions(x,conditions:[条件A,条件B,条件C])
struct MyConditions{
设myEps:Double=0.001
变量x:Double
var lessThan=[Double]()
var equalTo=[Double]()
变量greaterThan=[Double]()
init(x:Double){
self.x=x
}
变异func addConstraint(操作数:Double,op:String){
如果op==“”{
大于。追加(操作数)
}
}
func checkConstraints()->Bool{
乐山op酒店{
如果!(xop){
返回错误
}
}
对于大于的op{
如果!(x>op){
返回错误
}
}
返回真值
}
}
测试:

func feasibleHelloWorld(x: MyConditions) {
    if x.checkConstraints() {
        print("Hello world!")
    }
}

var x = MyConditions(x: 8)
x.addConstraint(100, op: "<")
x.checkConstraints() // true
feasibleHelloWorld(x) // Hello world!

x.addConstraint(8, op: "==")
x.checkConstraints() // true
feasibleHelloWorld(x) // Hello world!

x.addConstraint(7, op: "<")
x.checkConstraints() // false
feasibleHelloWorld(x) // ... nothing
func可行性HelloWorld(x:MyConditions){
如果x.checkConstraints(){
打印(“你好,世界!”)
}
}
var x=霉菌病(x:8)

x、 addConstraint(100,op:“除非您想要构建一个完整的语言,否则您必须弄清楚在这里您将允许哪些确切的操作

例如
=
的操作,基本上所有比较操作(
=
)都可以通过以下方式实现:

/* your X variable, might be var if you desire to change */
let x = 12

/* the array of conditions the user entered */
var conditions : [(((Int, Int) -> Bool), Int)] = []

/* some user input - read as e.g. "x > 2"*/
conditions.append((<, 100))
conditions.append((>, 2))
conditions.append((==, 12))

/* you evaluate all conditions in the following way */
let eval = conditions.map { $0(x, $1) }
let allTrue = !eval.contains(false)
/* allTrue would be true in this case because 12 < 100 && 12 > 2 && 12 == 12 */

您甚至可以使用从
“>”
(>)
等的普通旧字典映射,而不是使用函数解析运算符。

您的问题是关于Swift还是关于JavaScript?在某个地方,x不再是8?:)抱歉..忘了提及;这更多是关于这个问题背后的逻辑。闭包,这很好!@dfri I让eval=conditions.map{($0(x,$1)|$0(x-MY|TOL,$1)|$0(x+MY|TOL,$1))}
对于一些公差
我的TOL
?不应该把
搞砸,但是要允许对
=
检查进行公差。@dfri-hmm,这看起来不再那么漂亮了。我肯定会包括一个“小心”语句,但尚未包含任何特殊处理。@user1658080幸运的是,您有三个答案(简单,不太整洁)-->(有点复杂,非常优雅)。如果你有时间,我认为涵盖所有三个答案可能是一个有价值的练习,因为它们都使用不同的方法来解决同一个问题。从我的基本命令
struct
answer开始,然后进行更简洁的
enum
R-Menke解决方案,最后,尝试了解上面的luk2302真正优雅的解决方案。希望如果您通过增量更高级的解决方案来解决同一问题,那么将更容易掌握正在发生的事情。
struct MyConditions {
    let myEps: Double = 0.001
    var x: Double
    var lessThan = [Double]()
    var equalTo = [Double]()
    var greaterThan = [Double]()

    init(x: Double) {
        self.x = x
    }

    mutating func addConstraint(operand: Double, op: String) {
        if op == "<" {
            lessThan.append(operand)
        }
        else if op == "==" {
            equalTo.append(operand)
        }
        else if op == ">" {
            greaterThan.append(operand)
        }
    }

    func checkConstraints() -> Bool {
        for op in lessThan {
            if !(x < op) {
                return false
            }
        }
        for op in equalTo {
            if !(x - myEps < op && x + myEps > op) {
                return false
            }
        }
        for op in greaterThan {
            if !(x > op) {
                return false
            }
        }
        return true
    }
}
func feasibleHelloWorld(x: MyConditions) {
    if x.checkConstraints() {
        print("Hello world!")
    }
}

var x = MyConditions(x: 8)
x.addConstraint(100, op: "<")
x.checkConstraints() // true
feasibleHelloWorld(x) // Hello world!

x.addConstraint(8, op: "==")
x.checkConstraints() // true
feasibleHelloWorld(x) // Hello world!

x.addConstraint(7, op: "<")
x.checkConstraints() // false
feasibleHelloWorld(x) // ... nothing
/* your X variable, might be var if you desire to change */
let x = 12

/* the array of conditions the user entered */
var conditions : [(((Int, Int) -> Bool), Int)] = []

/* some user input - read as e.g. "x > 2"*/
conditions.append((<, 100))
conditions.append((>, 2))
conditions.append((==, 12))

/* you evaluate all conditions in the following way */
let eval = conditions.map { $0(x, $1) }
let allTrue = !eval.contains(false)
/* allTrue would be true in this case because 12 < 100 && 12 > 2 && 12 == 12 */
func getOperator(str: String) -> ((Int, Int) -> Bool)? {
    switch str {
    case "<":
        return (<)
    case ">":
        return (>)
    case "==":
        return (==)
    case "<=":
        return (<=)
    case ">=":
        return (>=)
    default:
        return nil
    }
}

func parseUserInput(str:String) -> (((Int, Int) -> Bool), Int) {
    var input = str as NSString
    input = input.stringByReplacingOccurrencesOfString(" ", withString: "")
    //let variable = input.substringToIndex(1) // in case you want more than one variable, but that will have to change the entire setup a bit
    // this has to be this "ugly" to incorporate both 1 char and 2 char long operators
    let operato = input.substringFromIndex(1).stringByTrimmingCharactersInSet(NSCharacterSet.alphanumericCharacterSet())
    let number = input.substringFromIndex(operato.lengthOfBytesUsingEncoding(NSASCIIStringEncoding) + 1)

    if let number = Int(number), op = getOperator(operato) {
        return (op, number)
    }

    return ((<, 999999)) // need some error handling here
}

conditions.append(parseUserInput("x > 123"))