-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDropTable.js
82 lines (71 loc) · 2.07 KB
/
DropTable.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
export class DropTable {
constructor(items) {
this._items = [];
this.weightedItems = {};
this.weightCached = false;
if(items) this.initializeWithItems(items);
}
initializeWithItems(items) {
this.items = items;
}
calculateWeightedItems() {
let weightedItems = [],
weighting = this.getTotalWeight(),
weightOffset = 0;
this._eachItem((item) => {
let itemWeight = (item.weight / weighting);
weightedItems.push({
weighting: itemWeight + weightOffset,
name: item.name,
data: item.data,
weightingOffset: weightOffset
});
weightOffset += itemWeight;
});
return weightedItems;
}
get items() {
return this._items;
}
set items(items) {
this._items = items;
this.weightCached = false;
this.weightedItems = this.calculateWeightedItems();
}
addItem(item) {
this.removeItem(item.name);
this.weightCached = false;
this.items.push(item);
this.weightedItems = this.calculateWeightedItems();
}
removeItem(itemName) {
let index = this.items.findIndex((item) => item.name == itemName);
if(index > -1) {
this.items.splice(index, 1);
this.weightCached = false;
this.weightedItems = this.calculateWeightedItems();
}
}
_eachItem(callbackFn) {
this.items.forEach(callbackFn);
}
getTotalWeight() {
if(this.weightCached) {
return this.totalWeight;
}
let totalWeight = 0;
this._eachItem((item) => {
totalWeight += item.weight;
});
this.totalWeight = totalWeight;
this.weightCached = true;
return this.totalWeight;
}
drop() {
let rand = Math.random();
return this.weightedItems.find((item) => {
return item.weighting > rand && item.weightingOffset < rand
});
}
}
export default DropTable;