0
\$\begingroup\$

In the below code, variable xAxis is re-initialized multiple times before every push into the array. How can i optimize this code?

var xAxis=1;
            vm.pnLreportingPlotData.push(plotModel.map(function(o){
                    return {x:xAxis++,y:o.PnLreporting};
                })
            );

            var xAxis=1;
            vm.var95PlotData.push(plotModel.map(function(o){
                    return { x:xAxis++, y:o.VaR95Total};
                })
            );

            var xAxis=1;
            vm.var99PlotData.push(plotModel.map(function(o){
                    var xAxis = 1;
                    return  { x:xAxis++, y:o.VaR99Total};
                })
            );
\$\endgroup\$
1
  • \$\begingroup\$ This question lacks context. What does this code accomplish? What are the inputs and outputs? See How to Ask. \$\endgroup\$ Commented Jul 26, 2017 at 16:43

1 Answer 1

2
\$\begingroup\$

You could remove the need for your xAxis variable through using the index when mapping:

vm.pnLreportingPlotData.push(plotModel.map(function (o, i) {
  return { x: i + 1, y: o.PnLreporting }
}

vm.var95Plotdata.push(plotModel.map(function (o, i) {
  return { x: i + 1, y: o.VaR95Total }
}

vm.var99PlotData.push(plotModel.map(function (o, i) {
  return { x: i + 1, y: o.VaR99Total }
}

Array.prototype.map provides three arguments, currentValue (o), index, and array (which isn't needed in our example)

N.B. you did not need to keep declaring xAxis after you had done so the first time (no need for the multiple var declarations, they could simply become xAxis = 1)

While the above answers your question of how to avoid redeclaring xAxis, I've added a few additional comments below:

Naming

You could possibly benefit from using more descriptive variable names. It is not immediately obvious what variables such as o represent. Likewise, i could be changed to index if you found it helped readability.

Consistency:

  • var95Plotdata uses lowercase 'd' for 'data', however var99PlotData capitializes it (is this a typo?)
  • VaR95Total capitalizes both 'V' and 'R' - can this be changed to be consistent with your view model or is this coming from an external api?

Extracting logic

Since the logic is almost identical besides property names, you could extract the logic if you wanted:

function getPlotData(property) {
  // Ideally renaming `o` to whatever it represents
  return plotModel.map(function (o, index) {
    return { x: index + 1, y: o[property] }
  }))
}

vm.pnLreportingPlotData.push(getPlotData('PnLreporting'))
vm.var95Plotdata.push(getPlotData('vaR95Total'))
vm.var99PlotData.push(getPlotData('VaR99Total'))
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.