-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWeightMap.js
46 lines (42 loc) · 1008 Bytes
/
WeightMap.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
export class WeightMap{
constructor(){
this.list = {};
}
get({x=0,y=0}={}){
const key = `x${x}y${y}`;
if(!this.list.hasOwnProperty(key)) return null;
return this.list[key]||0;
}
has({x=0,y=0}={}){
const key = `x${x}y${y}`;
if(!this.list.hasOwnProperty(key)) return false;
return true;
}
set({x=0,y=0,value=0}={}){
const key = `x${x}y${y}`;
this.list[key] = value;
}
setMany(weightMap){
if(!(weightMap instanceof WeightMap)){
throw new Error('setMany requires a WeightMap as parameter');
}
Object.keys(weightMap.list).forEach(key=>{
this.list[key] = weightMap[key];
});
}
getAll(){
return Object.keys(this.list)
.map(key=>{
const [,xs,ys] = key.split(/x|y/g);
return {x:+xs,y:+ys,value:this.list[key]};
});
}
reset(){
this.list = {};
}
clone(){
return Object.keys(this.list).reduce((sectors,key)=>{
sectors.list[key] = this.list[key];
},new WeightMap());
}
}