Support » Plugin: Gravity Forms MIN/MAX Calculation » Unexpected token when min or max is surrounded by parenthesis

  • Resolved quasibrodo

    (@quasibrodo)


    I get the following error

    VM2817:1 Uncaught SyntaxError: Unexpected token )
    at components.(/create-your-package/anonymous function).split.map (/wp-content/plugins/gravity-forms-minmax-master/gravityforms-minmax.min.js?ver=0.1.0:1:519)
    at Array.map (<anonymous>)
    at gravityforms-minmax.min.js?ver=0.1.0:1
    at Object.doHook (gravityforms.min.js?ver=2.4.6:1)
    at Object.applyFilters (gravityforms.min.js?ver=2.4.6:1)
    at GFCalc.runCalc (gravityforms.min.js?ver=2.4.6:1)
    at GFCalc.init (gravityforms.min.js?ver=2.4.6:1)
    at new GFCalc (gravityforms.min.js?ver=2.4.6:1)
    at HTMLDocument.<anonymous> (?state=Colorado&grow=1&processing=0&dispensary=0&distribution_delivery=0:535)
    at HTMLDocument.dispatch (jquery.js?ver=1.12.4:3)

    whenever I try to wrap the min or max functions in parentheses like so:
    (1 + MIN(2,3))
    When I leave them off, like so:
    1 + MIN(2,3)
    there is no problem.

Viewing 10 replies - 1 through 10 (of 10 total)
  • So I fixed the problem by editing the gravityforms-minmax.js and gravityforms-minmax.min.js

    I changed [\d\s\W]+ to [\d\s\W]+[^)] so it wouldn’t match with extra parentheses.

    I also put the matching and replacing in a while statement so that it would work with nested MIN and MAX functions, such as MAX(MIN(2,3), MIN(4,5))

    Finally instead of indexOf( ‘MIN’ ) I changed it to .indexOf( ‘MIN(‘ ) just so it would be less likely to try to parse incorrectly syntaxed functions.

    /**
    * Gravity Forms MIN/MAX Calculations
    * Version 0.3.1
    *
    * Add MIN/MAX functions to Gravity Forms calculation
    *
    * Thanks to @michaeldozark for gravityforms-exponent plugin:
    * https://github.com/michaeldozark/gravityforms-exponents
    *
    */

    gform.addFilter( ‘gform_calculation_result’, function( result, formulaField, formId, calcObj ) {

    /**
    * Only evaluate if the field has MIN/MAX present
    * Seaching for MIN(/MAX( to be less likely to try parsing incorrectly syntaxed formulae
    *
    * Technically we should be able to run any formulas through this without
    * breaking them, but this way we save some small amount of processing
    *
    * @link https://www.w3schools.com/jsref/jsref_indexof.asp
    * Description of indexOf method
    */

    if ( formulaField.formula.indexOf( ‘MIN(‘ ) > -1 || formulaField.formula.indexOf( ‘MAX(‘ ) > -1 ) {

    /**
    * Replace field tags with their associated values
    *
    * @param int formId The ID of the form in use
    * @param string formula The value of the “Formula” field entered in the form admin
    *
    * We are stripping out anything that is not a number, decimal, space, or simple arithmetical operator.
    * We are excluding any extra nested parenthesis that match might find [^)]
    *
    * @param object formulaField The current calculation field object
    * @var string fieldFormula
    */
    let fieldFormula = calcObj.replaceFieldTags( formId, formulaField.formula, formulaField ), pattern = /(MIN|MAX)\(([\d\s\W]+[^)])\s*\)/gi;

    /**
    * Sanitize the formula in case we have malicious user inputs. This
    * prevents malicious code getting passed to our eval call later in the
    * function
    *
    * @link https://www.w3schools.com/jsref/jsref_replace.asp
    * Description of replace method
    *
    * while is to facilitate parsing nested MIN and MAX functions
    */
    while ( fieldFormula.indexOf( ‘MIN(‘ ) > -1 || fieldFormula.indexOf( ‘MAX(‘ ) > -1 ) {

    let matches = fieldFormula.match(pattern), replaces = [];

    for(let i in matches) {
    let components = /(MIN|MAX)\(([\d\s\W]+[^)])\s*\)/gi.exec(matches[i]);
    let values = components[2].split(‘,’).map((value,index,array) => {
    return parseFloat(eval(value.trim()));
    });

    if (components[1] == “MIN”) replaces.push([matches[i], , Math.min(…values)]);
    if (components[1] == “MAX”) replaces.push([matches[i], , Math.max(…values)]);
    }

    for(let i in replaces) {
    fieldFormula = fieldFormula.replace(replaces[i][0], replaces[i][2]);
    }

    fieldFormula = fieldFormula.replace( /[^0-9\s\n\r\+\-\*\/\^\(\)\.](MIN|MAX)/g, ” );

    }

    /**
    * Set calculation result equal to evaluated string
    *
    * @link https://www.w3schools.com/jsref/jsref_eval.asp
    * Description of eval function
    */

    result = eval(fieldFormula);

    }

    return result;

    } );

    gform.addFilter(‘gform_calculation_result’,function(result,formulaField,formId,calcObj){if(formulaField.formula.indexOf(‘MIN(‘)>-1||formulaField.formula.indexOf(‘MAX(‘)>-1){let fieldFormula=calcObj.replaceFieldTags(formId,formulaField.formula,formulaField),pattern=/(MIN|MAX)\(([\d\s\W]+[^)])\s*\)/gi;while(fieldFormula.indexOf(‘MIN(‘)>-1||fieldFormula.indexOf(‘MAX(‘)>-1){let matches=fieldFormula.match(pattern),replaces=[];for(let i in matches){let components=/(MIN|MAX)\(([\d\s\W]+[^)])\s*\)/gi.exec(matches[i]);let values=components[2].split(‘,’).map((value,index,array)=>{return parseFloat(eval(value.trim()))});if(components[1]==”MIN”)replaces.push([matches[i],,Math.min(…values)]);if(components[1]==”MAX”)replaces.push([matches[i],,Math.max(…values)])}for(let i in replaces){fieldFormula=fieldFormula.replace(replaces[i][0],replaces[i][2])}fieldFormula=fieldFormula.replace(/[^0-9\s\n\r\+\-\*\/\^\(\)\.](MIN|MAX)/g,”)}result=eval(fieldFormula)}return result})

    Plugin Author George Mandis

    (@georgemandis)

    Hi @quasibrodo,

    Thanks so much for the feedback! I really appreciate these.

    Would you have any interest in submitting a pull request with your changes to the GitHub repository?

    https://github.com/snaptortoise/gravity-forms-minmax

    No pressure if you don’t have the time or want to. I’ll roll them in eventually but don’t have a lot of time right now.

    Best,
    George

    Was a fix included in 0.4.0? I’m getting this today while running 0.4.0 that seems similar:

    Uncaught SyntaxError: Unexpected token )
        at gravityforms-minmax.js?ver=0.1.0:62
        at Array.map (<anonymous>)
        at gravityforms-minmax.js?ver=0.1.0:61
        at Object.doHook (gravityforms.min.js?ver=2.4.9:1)
        at Object.applyFilters (gravityforms.min.js?ver=2.4.9:1)
        at GFCalc.runCalc (gravityforms.min.js?ver=2.4.9:1)
        at GFCalc.init (gravityforms.min.js?ver=2.4.9:1)
        at new GFCalc (gravityforms.min.js?ver=2.4.9:1)
        at HTMLDocument.<anonymous> ((index):803)
        at HTMLDocument.dispatch (jquery.js?ver=1.12.4-wp:3)

    I just looked at the repo on github, and I see that a fix was made in 0.4.0 for this problem. The fix does not seem to use the code provided above, and I think I am still getting a JavaScript error because I have the MIN and MAX functions nested inside multiple levels of parentheses.

    This kills the whole form. The whole thing remains invisible.

    Quickly pasting in the solution above fixes the error that I get using 0.4.0, but I have not yet tested if the formula works as expected.

    Plugin Author George Mandis

    (@georgemandis)

    Hi @salzano,

    I found the code above introduced other problems.

    Can you show me what your formula looks like?

    Sure. This is a convenience fee calculation to get 3% + $.30 added to the form total so an online payment includes the fee that transactions costs. I’m using MAX(1, x) to make sure a quantity isn’t zero. I could create another convenience fee calculation and hide this one with conditional logic if this plugin is no longer going to work in this calculation.

    ((.3 + (({Vehicle type:21} * MAX(1,{Vehicle count:94}) ) + ({Track License (Price):125.2}*{Track License Quantity:126}) + ({Pit License (Price):127.2} * {Pit License Quantity:128}) + ({Camp License (Price):129.2} * {Camp License Quantity:130}) + ({Extra Chairs: (Price):22.2} * {Extra Chairs: (Quantity):22.3}) + ({Extra Tables: (Price):24.2} * {Extra Tables: (Quantity):24.3}) + {Extra Power::97} + ({Extra Pit Passes: (Price):95.2} * {Quantity:96}) + ({Tent quantity:104}*{Tent (Price):103.2}) + {Shared Vehicle Fee (Price):87.2})) * .035))

    Hello @salzano

    I’m pretty certain you do in fact have an extra ‘)’.

    Unfortunately the calculation field validation isn’t terribly robust. It’ll miss stuff like this.

    (
    (
    .3 +
    (
    ({Vehicle type:21} * MAX(1,{Vehicle count:94}) ) +
    ({Track License (Price):125.2}*{Track License Quantity:126}) +
    ({Pit License (Price):127.2} * {Pit License Quantity:128}) +
    ({Camp License (Price):129.2} * {Camp License Quantity:130}) +
    ({Extra Chairs: (Price):22.2} * {Extra Chairs: (Quantity):22.3}) +
    ({Extra Tables: (Price):24.2} * {Extra Tables: (Quantity):24.3}) +
    {Extra Power::97} +
    ({Extra Pit Passes: (Price):95.2} * {Quantity:96}) +
    ({Tent quantity:104}*{Tent (Price):103.2}) +
    {Shared Vehicle Fee (Price):87.2}
    )
    )
    * .035
    )
    )//this final parenthesis is extra

    Thanks! I’ll do some more testing with version 0.4.0.

    Plugin Author George Mandis

    (@georgemandis)

    Thanks for stepping in and helping out @quasibrodo!

    I think the field validation is a little smarter than the “actual” validation and parsing that happens behind the scenes. It can handle an extra parenthesis, but my code chokes on it.

    I’ll make a note and try to see if I can fix the issue, but can’t promise a real quick turnaround.

Viewing 10 replies - 1 through 10 (of 10 total)
  • The topic ‘Unexpected token when min or max is surrounded by parenthesis’ is closed to new replies.