Skip to content

Commit 4ad78b3

Browse files
committed
refactor: improve Graham implementation
1 parent 368cfca commit 4ad78b3

File tree

1 file changed

+13
-17
lines changed

1 file changed

+13
-17
lines changed

src/graphics/graham.js

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,8 @@
99
const sa = slope(p, a);
1010
const sb = slope(p, b);
1111
[[sa, a], [sb, b]].forEach(e => {
12-
if (!memo.has(e[0])) {
13-
memo.set(e[0], new Set());
14-
}
15-
memo.get(e[0]).add(e[1]);
12+
const el = memo.get(e[0]);
13+
if (!el || dist(p, el) < dist(p, e[1])) memo.set(e[0], e[1]);
1614
});
1715
return sa - sb;
1816
};
@@ -50,21 +48,19 @@
5048
if (a.x < c.x) return a;
5149
return c;
5250
});
53-
const memo = new Map();
54-
const points = all.sort(sort.bind(null, p, memo)).filter(c => {
55-
const s = slope(p, c);
56-
// Liner check, can consider more efficient data structure
57-
const set = Array.from(memo.get(s));
58-
return !set.some(e => dist(p, e) > dist(p, c));
59-
});
6051

52+
const memo = new Map();
6153
const stack = [];
62-
points.forEach(p => {
63-
while (stack.length > 1 && ccw(stack[stack.length - 2], stack[stack.length - 1], p) < 0) {
64-
stack.pop();
65-
}
66-
stack.push(p);
67-
});
54+
55+
all
56+
.sort(sort.bind(null, p, memo))
57+
.filter(c => memo.get(slope(p, c)) === c)
58+
.forEach(p => {
59+
while (stack.length > 1 && ccw(stack[stack.length - 2], stack[stack.length - 1], p) < 0)
60+
stack.pop();
61+
stack.push(p);
62+
});
63+
6864
return stack;
6965
};
7066

0 commit comments

Comments
 (0)