user3101259
user3101259

Reputation: 91

Calling a function which returns several values

If a function returns more than one calculation and it's convenient to reuse that one function in few separate instances, is it best to store the result of the calculations in an internal array and just pull out of the array a calculation that's needed on that particular call or is there a more efficient way?

var calcFunction = function() {

    var ar = [];

    var calcA = ...
    ar.push(calcA);

    var calcB = ...
    ar.push(calcA);

    return ar;

}

Upvotes: 2

Views: 69

Answers (2)

cbayram
cbayram

Reputation: 2259

Here are options off the top of my head in order of my preference. Performance, if truly releavant, you should benchmark. Preference depends on your code and its purpose.

        // If independent and appropriate, split it into two separate functions
        // modularization into smaller reusable building blocks is good
        var calcAFunction = function() {
          var calcA = ...
          return calcA;
        }

        var calcBFunction = function() {
          var calcB = ...
          return calcB;
        }

        // Returning an array
        var calcFunction = function() {

          var ar = [];

          var calcA = ...
          ar.push(calcA);

          var calcB = ...
          ar.push(calcA);

          return ar;

        }
        // Returning an object, disadvantage you must maintain key names as opposed to index 
        var calcFunction = function() {

          var o = {};

          var calcA = ...
          o.key1 = calcA;

          var calcB = ...
          o["key2"] = calcB;

          return o;

        }
        // Calling it with a callback function
        var calcFunction = function(cb) {

          var o = {};

          var calcA = ...

          var calcB = ...

          cb(calcA, calcB)

        }
        calcFunction(function(A, B) {})

UPDATE

        // Returning an object, disadvantage you must maintain key names as opposed to index 
        var calcFunction = function() {

          var o = {};

          var calcA = ...
          o.key1 = calcA;

          var calcB = ...
          o["key2"] = calcB;

          return o;

        }

        var retObj = calcFunction();
        //you can access retObj.key1 and retObj.key2

Upvotes: 1

scrblnrd3
scrblnrd3

Reputation: 7416

If you're function is really long, it'll be much more efficient to use the array every time, however, this distance gets shorter and shorter as the function gets shorter. However, this isn't the only reason to use the array. Calling the function several times with the same values is essentially code duplication, which is a standard code smell.

Overall, if you can call a method as few times as possible, you've done your job right.

Upvotes: 2

Related Questions