I am unsure of why the this in the second case of the Sort methods sort compare function is undefined? I managed to get the correct this by using an arrow function.
var SortTypeEnum = {
SortByGold: 1,
SortByOwnership: 2,
};
class Resource {
constructor(Gold, IsOwned) {
this.Gold = Gold;
this.IsOwned = IsOwned;
}
}
class ResourceInventory {
constructor(Inventory, SortedDescending = false) {
this.Inventory = Inventory;
this.SortedDescending = SortedDescending;
}
Sort(sortType) {
switch (sortType) {
case SortTypeEnum.SortByOwnership:
this.Inventory.sort(function (lhs, rhs) {
return rhs.IsOwned - lhs.IsOwned;
});
break;
case SortTypeEnum.SortByGold:
this.Inventory.sort(function (lhs, rhs) {
return this.SortedDescending ? rhs.Gold - lhs.Gold : lhs.Gold - rhs.Gold;
});
this.SortedDescending = !this.SortedDescending;
break;
}
}
}
var resources = [new Resource(1, false), new Resource(3, false), new Resource(2, true)];
var inv = new ResourceInventory(resources);
inv.Sort(SortTypeEnum.SortByGold);