-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutil.js
67 lines (56 loc) · 1.44 KB
/
util.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
const CODEPOINT_a = 'a'.codePointAt(0);
const CODEPOINT_1 = '1'.codePointAt(0);
function isString(value) {
return typeof value === 'string' || value instanceof String;
}
/// Converts algebraic location notation to [rank, file] (0-indexed)
function algebraicToSpace(algebraic) {
let file = algebraic.toLowerCase().codePointAt(0) - CODEPOINT_a;
let rank = parseInt(algebraic[1]) - 1;
return [rank, file];
}
function spaceToAlgebraic([rank, file]) {
return String.fromCharCode(file + CODEPOINT_a, rank + CODEPOINT_1);
}
function toSpace(location) {
if (isString(location)) {
return algebraicToSpace(location);
}
else {
return location
}
}
function toAlgebraic(location) {
if (isString(location)) {
return location;
}
else {
return spaceToAlgebraic(location);
}
}
function otherColor(color) {
return color == 'white'? 'black' : 'white';
}
function sameLocation(l1, l2) {
let [r1, f1] = toSpace(l1);
let [r2, f2] = toSpace(l2);
return r1 === r2 && f1 === f2;
}
function straightLine(l1, l2) {
let [r1, f1] = toSpace(l1);
let [r2, f2] = toSpace(l2);
if (Math.abs(r2 - r1) === Math.abs(f2 - f1) || r1 === r2 || f1 === f2) {
let rankDir = Math.sign(r2 - r1);
let fileDir = Math.sign(f2 - f1);
let path = [];
let r = r1 + rankDir;
let f = f1 + fileDir;
while (r != r2 || f != f2) {
path.push([r, f]);
r += rankDir;
f += fileDir;
}
return path;
}
else return [];
}