-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.js
90 lines (77 loc) · 2.21 KB
/
store.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
83
84
85
86
87
88
89
90
import { getViolatingPoints } from "./algo/Check.js";
import { Point } from "./Point.js";
class Store {
constructor(points) {
// mapping of x,y coordinates to its type
this.points = points || {};
this.violatingPoints = [];
}
togglePoint(point) {
const existingPoint = this.points[point.toString()];
// Remove/add from the mapping
if (existingPoint) {
// cannot overwrite a grid point with added point
if (point.type === Point.ADDED && existingPoint.type === Point.GRID) return;
delete this.points[existingPoint.toString()];
} else {
this.points[point.toString()] = point;
}
this.violatingPoints = [];
// check violations interactively
this.computeCheck();
}
computeSuperset(algorithm) {
this.clearAddedPoints();
algorithm(Object.values(this.points)).forEach((point) =>
this.points[point.toString()] = point
);
this.computeCheck();
}
computeCheck() {
this.violatingPoints = getViolatingPoints(Object.values(this.points));
return this.violatingPoints;
}
clearPoints() {
this.points = {};
this.violatingPoints = [];
}
clearAddedPoints() {
for (const point of Object.values(this.points)) {
if (point.type === Point.ADDED) {
delete this.points[point.toString()];
}
}
this.computeCheck();
}
toJsonString() {
return JSON.stringify(this.points);
}
/**
* Returns hash representation of list of points
*/
hash() {
return Object.values(this.points)
// .filter(p => p.type === Point.GRID)
.map(p => `(${p.x},${p.y}${(p.type==Point.GRID)?"":",1"})`).join(';');
}
/**
* Parse hashed list of points
*
* @param {String} hashedPoints list of points formatted using `Store.hash`
*/
static unhash(hashedPoints) {
return hashedPoints
.split(';')
.reduce((points, p) => {
const m = p.trim().match(/\((-?[\d]+),\s*(-?[\d]+)(,\s*(-?[\d]+))?\)/);
if (m) {
let type = Point.GRID;
if (m[4]=="1") type = Point.ADDED;
const point = new Point(parseInt(m[1]), parseInt(m[2]), type);
points[point.toString()] = point;
}
return points;
}, {});
}
}
export { Store };