Completed
Push — master ( 78b239...b3de34 )
by Andres
37s
created

upgrades.js ➔ ... ➔ sortFunc   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
nc 3
dl 0
loc 10
rs 9.4285
nop 2
1
/**
2
 upgrades
3
 Component that handles upgrades.
4
5
 @namespace Components
6
 */
7
'use strict';
8
9
angular.module('game').component('upgrades', {
10
  templateUrl: 'views/upgrades.html',
11
  controller: ['state', 'visibility', 'upgrade', 'data', upgrades],
12
  controllerAs: 'ct'
13
});
14
15
function upgrades(state, visibility, upgrade, data) {
16
  let ct = this;
17
  ct.state = state;
18
  ct.data = data;
19
  let sortFunc = [
20
    function(a,b){
21
      if(data.upgrades[a].name === data.upgrades[b].name){
22
        return data.upgrades[a].price - data.upgrades[b].price;
23
      }
24
      if(data.upgrades[a].name < data.upgrades[b].name){
25
        return -1;
26
      }else{
27
        return 1;
28
      }
29
    },
30
    (a,b) => data.upgrades[a].price - data.upgrades[b].price
31
  ];
32
33
  // tries to buy all the upgrades it can, starting from the cheapest
34
  ct.buyAll = function (slot) {
35
    let currency = data.elements[slot.element].main;
36
    let cheapest;
37
    let cheapestPrice;
38
    do{
39
      cheapest = null;
40
      cheapestPrice = Infinity;
0 ignored issues
show
Comprehensibility Best Practice introduced by
You seem to be aliasing the built-in name Infinity as cheapestPrice. This makes your code very difficult to follow, consider using the built-in name directly.
Loading history...
41
      for(let up of ct.visibleUpgrades(slot, data.upgrades)){
42
        let price = data.upgrades[up].price;
43
        if(!slot.upgrades[up] &&
44
          price <= state.player.resources[currency].number){
45
          if(price < cheapestPrice){
46
            cheapest = up;
47
            cheapestPrice = price;
48
          }
49
        }
50
      }
51
      if(cheapest){
52
        upgrade.buyUpgrade(state.player,
53
          slot.upgrades,
54
          data.upgrades[cheapest],
55
          cheapest,
56
          cheapestPrice,
57
          currency);
58
      }
59
    }while(cheapest);
60
  };
61
62
  ct.buyUpgrade = function (name, slot) {
63
    let price = data.upgrades[name].price;
64
    let currency = data.elements[slot.element].main;
65
    upgrade.buyUpgrade(state.player,
66
      slot.upgrades,
67
      data.upgrades[name],
68
      name,
69
      price,
70
      currency);
71
  };
72
73
  ct.visibleUpgrades = function(slot) {
74
    return visibility.visible(data.upgrades, isBasicUpgradeVisible, slot, sortFunc[state.player.options.sortIndex]);
75
  };
76
77
  function isBasicUpgradeVisible(name, slot) {
78
    let isVisible = visibility.isUpgradeVisible(name, slot, data.upgrades[name]);
79
    return isVisible && (!state.player.options.hideBought || !slot.upgrades[name]);
80
  }
81
}
82