Battle_Slug
Battle_Slug

Reputation: 2105

How to optimize the code?

I have two functions that are basically the same - they iterate over some array. The difference is what happens inside the loop.

    func1: function () {
        var result = "";
        for (var i = 0; i < array1.length; i++) {
            result = result + array1[i].field1 + ', ';

        }
        if (result.length > 0) {
            return result.substring(0, result.length - 2);
        } else return ""
    },

    func2: function () {
        var result = "";
        for (var i = 0; i < array2.length; i++) {
            result = result + array2[i].field2 + ', ';

        }
        if (result.length > 0) {
            return result.substring(0, result.length - 2);
        } else return ""
    },

What is the correct way to say make it just one function, or to make both inherit some common code? I see a solution to make it just one function and provide different parameters:

func: function (array, fieldName) {
    var result = "";
    for (var i = 0; i < array.length; i++) {
        result = result + array[i].[fieldName] + ', ';
    }
    if (result.length > 0) {
        return result.substring(0, result.length - 2);
    } else return ""
},

But something tells me it's ugly. What is correct way to do it?

Upvotes: 0

Views: 94

Answers (2)

Veera
Veera

Reputation: 33192

Old school:

function pluckAndJoin(arr, attr) {
  var i,
      len = arr.length,
      res = [];
  for(i=0; i<len; i++){
        res.push(arr[i][attr]);
  }
  return res.join(', ');
}

console.log(pluckAndJoin([{name:'Hello'}, {name:'World'}], 'name'));

Upvotes: 2

Phil
Phil

Reputation: 165059

Much easier than concatenating and truncating...

func: function(array, fieldName) {
    return array.map(a => a[fieldName]).join(', ');
}

Upvotes: 6

Related Questions