iOS gets the calculation results of string math formulas, string conditional operations, and logical operations

foreword

During the development, we encountered multiple input box calculation linkages, and automatically calculated the results through the formula returned by the server and displayed them in the corresponding input boxes.

For example the following formula

@"{width}*{height}*0.5+1"

Or more complex formulas, the {width} code in the code replaces the value, and the following string is obtained after replacement in the code logic

@"20*30*0.5+1"

It is possible that the formula in actual business is more complicated than this.
Just a colleague said that JavaScript has a function eval that can solve the above problems and get the result directly.
Here comes the inspiration. Haha JavaScriptCore...
don't say much and go directly to the code

+ (CGFloat)evalCaculateStringFormulaJavaScript:(NSString *)string{
    
    
    //去空格
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (string.length == 0) {
    
    
        return 0;
    }
    JSContext *context = [[JSContext alloc] init];
    JSValue *jsFunction = [context evaluateScript:[NSString stringWithFormat:@"(function(){  return eval(%@) })",string]];
    return [[[jsFunction callWithArguments:nil] toNumber] floatValue];
}

If the return value is a floating-point number, there may be precision problems, which can be handled appropriately, so I won’t say much here.

String Conditional and Logical Operations

The method is basically the same as above, but remember to add single quotes for string comparison to conform to the JavaScript writing method.
for example

//字符串对比结果
@"'ac'=='ac'"
@"'ac'=='dc'"

There is no need for numerical comparison.
code show as below

+ (BOOL)evalJavaScript:(NSString *)string{
    
    
    BOOL result = false;
    //去空格
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (string.length == 0) {
    
    
        return result;
    }
    
    JSContext *context = [[JSContext alloc] init];
    JSValue *jsFunction = [context evaluateScript:[NSString stringWithFormat:@"(function(){  return eval(%@) })",string]];
    return [[jsFunction callWithArguments:nil] toBool];
}

Guess you like

Origin blog.csdn.net/sky_long_fly/article/details/126628251