Convex Hull Implementation in TypeScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Convex Hull runs in O(n log n) time and O(n) space, in TypeScript as in every other language.
- ✓TypeScript adds no runtime, so the machinery is the same Array.prototype.sort with push and pop.
- ✓Reviewers want the tuple type rather than number[], and readonly on every input array so the function provably cannot sort in place.
- ✓The TypeScript trap: Types are erased, so the one place they cannot help is the boundary -- and this algorithm lives at one.
- ✓Types cost nothing at runtime, but the emit does. for (const p of seq) compiled against an ES5 target with downlevelIteration becomes a helper that allocates an iterator object per call; target ES2015 or later and the allocation disappears.
What Convex Hull actually is
Convex Hull in TypeScript: what you actually reach for
TypeScript implementation
export type Point = readonly [x: number, y: number];
const cross = (o: Point, a: Point, b: Point): number =>
(a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
function chain(seq: readonly Point[]): Point[] {
const h: Point[] = [];
for (const p of seq) {
for (;;) {
const a = h.at(-2);
const b = h.at(-1);
// .at() always returns Point | undefined (lib.es2022); h[h.length - 2]
// only does under noUncheckedIndexedAccess. Either way: no `!`.
if (a === undefined || b === undefined) break;
if (cross(a, b, p) > 0) break;
h.pop();
}
h.push(p);
}
h.pop();
return h;
}
export function convexHull(points: readonly Point[]): Point[] {
const pts = [...points].sort((p, q) => p[0] - q[0] || p[1] - q[1]);
if (pts.length < 3) return pts;
return [...chain(pts), ...chain([...pts].reverse())];
}
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(n log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Convex Hull?
TypeScript adds no runtime, so the machinery is the same Array.prototype.sort with push and pop. What it adds is shape: type Point = readonly [x: number, y: number], a labelled tuple, or a readonly { x: number; y: number } interface, so the compiler stops you handing in a number[] of unknown length. On DefinitelyTyped, @types/d3-polygon declares polygonHull as taking an array of [number, number] pairs and returning that array type or null. The | null is what makes the typed binding worth using: it forces the degenerate fewer-than-three case to be handled at compile time.
What is the most common TypeScript mistake when implementing Convex Hull?
Types are erased, so the one place they cannot help is the boundary -- and this algorithm lives at one. JSON.parse returns any, so const pts = JSON.parse(body) as Point[] type-checks perfectly while handing you objects, strings, or two-element arrays that are actually one element long. A missing second slot makes p[1] undefined, the cross product becomes NaN, and NaN in a comparator is the worst possible value: it is neither negative, zero nor positive, so sort produces an arbitrary permutation instead of throwing. The hull comes out wrong with no stack trace anywhere in it. Validate at the edge with zod or a hand-written type guard; as is not validation.
How does Convex Hull actually perform in TypeScript?
Types cost nothing at runtime, but the emit does. for (const p of seq) compiled against an ES5 target with downlevelIteration becomes a helper that allocates an iterator object per call; target ES2015 or later and the allocation disappears. Spreads such as [...pts].reverse() lower to __spreadArray under old targets, copying twice instead of once. const enum inlines but breaks under isolatedModules, so most codebases forbid it. Everything else -- hidden classes, comparator monomorphism, packed-array behaviour -- is V8's, and is identical to plain JavaScript. Time complexity is O(n log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what GitHub Copilot offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.