JSLint “eval is evil.” alternatives

后端 未结 7 1349
别那么骄傲
别那么骄傲 2021-02-13 22:49

I am have some JavaScript functions that run on both the client (browser) and the server (within a Java Rhino context). These are small functions - basically little validators

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-13 23:20

    DRY is definitely something I agree with, however there is a point where copy+pasting is more efficient and easy to maintain than referencing the same piece of code.

    The code you're saving yourself from writing seems to be equivalent to a clean interface, and simple boiler plate. If the same code is being used on both the server and the client, you could simply pass around the common pieces of the function, rather than the whole function.

    Payload:
    {
        "name": "phoneNumber",
        "type": "regexCheck",
        "checkData": "/^\\+?([0-9\\- \\(\\)])*$/"
    }
    
    if(payload.type === "regexCheck"){
        const result = validPhoneFormat(fullObject, value, payload.checkData)
    }
    
    function validPhoneFormat(fullObject, value, regexPattern) {
    
        if (value && value.length && !regexPattern.test(value))
            return [ {"policyRequirement": "VALID_PHONE_FORMAT"}];
        else
            return [];
    }
    

    This would give you the ability to update the regex from a single location. If the interface changes it does need to be updated in 2 places, but I wouldn't consider that a bad thing. If the client is running code, why hide the structure?

    If you really, really want to keep both the object structure and the patterns in one place - extract it to a single API. Have a "ValidatePhoneViaRegex" api endpoint which is called by all places you'd be passing this serialized function to.

    If all of this seems like too much effort, set jslint to ignore your piece of code:

    "In JSHint 1.0.0 and above you have the ability to ignore any warning with a special option syntax. The identifier of this warning is W061. This means you can tell JSHint to not issue this warning with the /*jshint -W061 */ directive.

    In ESLint the rule that generates this warning is named no-eval. You can disable it by setting it to 0, or enable it by setting it to 1."

    https://github.com/jamesallardice/jslint-error-explanations/blob/master/message-articles/eval.md

    I would prefer to see copy+pasted code, a common api, or receiving parameters and copy+pasted boiler plate than magical functions passed in from the server to be executed.

    What happens if you get a cross-browser compatibility error with one of these shared functions?

提交回复
热议问题