1

I have a function and it works just fine, but codacy inspection says it is bad practice to do so. I understand that it even looks unsafe, but I cannot come up with how to do it another, better, way.

    function getCount(i) {

        var iCount = iCount || 0;

        for (var item in this.items) {
            for (var level1 in this.items[item]) {
                for (var level2 in this.items[item][level1]) {
                    for (var level3 in this.items[item][level1][level2]) {
                        if (this.items[item][level1][level2][level3] == i) {
                            iCount++;
                        }
                    }
                }
            }
        }
        return iCount;
    }

After Icycool's advices I came up with something more acceptable. I tried to use forEach loop, but it didn't work so I decided to use a fori. Though it is not perfect it'll do for now:

    function getCount(i) {
        var iCount = iCount || 0;
            for (var y = 0; y < this.items["content"].length; y++) {
                if (this.items["content"][y]["custom_object"]["id"] === i) {
                    iCount++;
                }
            }
        return iCount;
    }
pedrorijo91
  • 7,635
  • 9
  • 44
  • 82
Bobby
  • 534
  • 3
  • 7
  • 21

1 Answers1

1

You can simplify it with a recursive function.

function getCount(i, items) {
  var count = 0;

  items.forEach(function(item) {
    if (item.isArray) count += getCount(i, item);
    else if (item == i) count++;
  });

  return count;
}
Icycool
  • 7,099
  • 1
  • 25
  • 33
  • It wasn't working because of 'items' instead of 'this.items', but even after I change that I get an error. It says "TypeError: self.items.forEach is not a function". What am I doing wrong here? Your code looks correct and nice, I'd like to swith to it. – Bobby Jul 05 '17 at 10:26
  • 1
    If you need to use `this`, you'll need to create a outer layer function like `function getCountOuter(i) { getCount(i, this.items) }` – Icycool Jul 05 '17 at 11:49
  • Now I get no errors but function doesn't work, I get NaN where my monster function returns a number. – Bobby Jul 05 '17 at 13:02
  • @Bobby can you provide some sample data? – Icycool Jul 05 '17 at 15:10