Why operator '+' inside functions does not modify * def made variables?

五迷三道 提交于 2019-12-11 12:12:44

问题


I'm trying to process a list of json-s that I got as an answer from an API.

[
  {
    "originalEstimate": "16h",
    "remainingEstimate": "9h",
    "timeSpent": "7h"
  },
  {
    "originalEstimate": "64h",
    "remainingEstimate": "63h",
    "timeSpent": "1h"
  }
]

I have to sum the fields and I came up with a code for it, but it seems like it does not modify the mySum variable.

For this example, I just used the 'originalEstimate'.

I tried to add manually the elements and that works. Ex.: (parseFloat(getNum(json[0].originalEstimate))) == 16.0

getNum is a function that cuts the 'h' down from the string.

The code looks like this:

    * def getNum = function (a)  {return a.substring(0,a.length()-1)}
* text raw =
    """
  [
    {
      "originalEstimate": "16h",
      "remainingEstimate": "9h",
      "timeSpent": "7h"
    },
    {
      "originalEstimate": "64h",
      "remainingEstimate": "63h",
      "timeSpent": "1h"
    }
  ]
  """
    * json json = raw
    * def mySum = 0
    * def fn = function(x) {mySum = mySum + (parseFloat(getNum(x.originalEstimate)))}
    * eval karate.forEach(json,fn)
    * print mySum

I expected to see 80.0 as originalEstimate sum but I received 0. Also, it runs perfectly, just does not modify the mySum


回答1:


Yes, when you declare a function, variables are locked to the value at the time the function was declared. The solution is use karate.get() and karate.set():

* def getNum = function(x){ return x.substring(0, x.length() - 1) }
* def sum = 0
* def fun = function(x){ var temp = karate.get('sum') + parseFloat(getNum(x.originalEstimate)); karate.set('sum', temp) }
* def response =
"""
[
  {
    "originalEstimate": "16h",
    "remainingEstimate": "9h",
    "timeSpent": "7h"
  },
  {
    "originalEstimate": "64h",
    "remainingEstimate": "63h",
    "timeSpent": "1h"
  }
]
"""
* eval karate.forEach(response, fun)
* print sum


来源:https://stackoverflow.com/questions/55920830/why-operator-inside-functions-does-not-modify-def-made-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!