-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExistenceMap.js
51 lines (46 loc) · 1.08 KB
/
ExistenceMap.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
export class ExistenceMap{
constructor(){
this.list = {};
}
get({x=0,y=0}={}){
const key = `x${x}y${y}`;
if(!this.list.hasOwnProperty(key)) return false;
return this.list[key];
}
set({x=0,y=0}={}){
const key = `x${x}y${y}`;
this.list[key] = true;
}
unset({x=0,y=0}={}){
const key = `x${x}y${y}`;
this.list[key] = false;
}
setMany(existenceMap){
if(!(existenceMap instanceof ExistenceMap)){
throw new Error('setMany requires an ExistenceMap as parameter');
}
Object.keys(existenceMap.list).forEach(key=>{
this.list[key] = true;
});
}
// only return those that are truthy
getAll(){
const list = Object.keys(this.list)
.reduce((array,key)=>{
if(this.list[key]){
const [,xs,ys] = key.split(/x|y/g);
array.push({x:+xs,y:+ys});
} //end if
return array;
},[]);
return list;
}
reset(){
this.list = {};
}
clone(){
return Object.keys(this.list).reduce((sectors,key)=>{
sectors.list[key] = this.list[key];
},new ExistenceMap());
}
}