time for a snapshot
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
# Step 01 — Vectors
|
||||
|
||||
> You know this cold. The point of this step is to make the red→green loop
|
||||
> automatic, not to teach you arithmetic. Blast through it.
|
||||
|
||||
## Concept
|
||||
|
||||
A **vector** here is nothing mystical: a pair of numbers `(x, y)`. We use the
|
||||
same value to mean two different things depending on context:
|
||||
|
||||
- a **position** — a point in the world.
|
||||
- a **displacement / velocity** — an arrow: "move this much in x, this much in y."
|
||||
|
||||
That's it. All of 2D physics is built on adding, subtracting, and scaling these
|
||||
pairs.
|
||||
|
||||
- `add(a, b)` → `(a.x + b.x, a.y + b.y)` — apply an arrow to a point.
|
||||
- `sub(a, b)` → `(a.x - b.x, a.y - b.y)` — the arrow that points *from b to a*.
|
||||
- `scale(a, s)` → `(a.x * s, a.y * s)` — make an arrow longer/shorter.
|
||||
|
||||
> Note: we return **new** objects (pure functions) here for clarity. Your real
|
||||
> engine mutates vectors in place to avoid garbage collection — that's a speed
|
||||
> optimization we'll deliberately ignore until the very end.
|
||||
|
||||
## Task
|
||||
|
||||
Implement `vec`, `add`, `sub`, and `scale` in `vector.ts`.
|
||||
|
||||
```sh
|
||||
bun test workshop/steps/01-vectors
|
||||
```
|
||||
@@ -0,0 +1,25 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { add, scale, sub, vec } from "./vector.ts";
|
||||
|
||||
test("vec builds a vector", () => {
|
||||
expect(vec(2, 3)).toEqual({ x: 2, y: 3 });
|
||||
});
|
||||
|
||||
test("add is component-wise", () => {
|
||||
expect(add(vec(1, 2), vec(3, 4))).toEqual({ x: 4, y: 6 });
|
||||
});
|
||||
|
||||
test("sub is component-wise", () => {
|
||||
expect(sub(vec(5, 5), vec(1, 2))).toEqual({ x: 4, y: 3 });
|
||||
});
|
||||
|
||||
test("scale multiplies both components", () => {
|
||||
expect(scale(vec(2, 3), 2)).toEqual({ x: 4, y: 6 });
|
||||
expect(scale(vec(2, 3), 0)).toEqual({ x: 0, y: 0 });
|
||||
});
|
||||
|
||||
test("inputs are not mutated (pure functions)", () => {
|
||||
const a = vec(1, 2);
|
||||
add(a, vec(3, 4));
|
||||
expect(a).toEqual({ x: 1, y: 2 });
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
export type Vec = { x: number; y: number };
|
||||
|
||||
/** Build a vector from two numbers. */
|
||||
export function vec(x: number, y: number): Vec {
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
/** a + b (component-wise) */
|
||||
export function add(a: Vec, b: Vec): Vec {
|
||||
return {
|
||||
x: a.x + b.x,
|
||||
y: a.y + b.y,
|
||||
};
|
||||
}
|
||||
|
||||
/** a - b (component-wise) */
|
||||
export function sub(a: Vec, b: Vec): Vec {
|
||||
return {
|
||||
x: a.x - b.x,
|
||||
y: a.y - b.y,
|
||||
};
|
||||
}
|
||||
|
||||
/** a scaled by the scalar s */
|
||||
export function scale(a: Vec, s: number): Vec {
|
||||
return {
|
||||
x: a.x * s,
|
||||
y: a.y * s,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user