Capstone: utils library
| The spec | |
| Pure functions | |
| Exported types | |
| Assert tests |
The spec
The utils library ships three pure helpers with exported types: a slug maker, a result wrapper, and a list formatter. No file access and no network calls are allowed inside.
Pure functions make the perfect first library because every test is just input and output. The spec fits on an index card, yet it teaches exports, types, and tests end to end.
Pure functions
A pure function returns the same output for the same input and touches nothing outside itself. Same input, same output, every run.
Build slug from trim, lower case, split, and join in one chain. Each step is a small documented string operation, so the whole pipeline reads aloud.
export function slug(title: string): string {
return title.trim().toLowerCase().split(" ").join("-");
}
const out: string = slug("Hello World");
console.log(out);
Exported types
Export the types next to the functions so consumers can annotate their own code. A Result type with an ok flag and a message covers most helper outcomes.
Keep exported types small and exact, then let callers compose them. A library with three precise types beats one with a bag of loose options.
export type Result = {
ok: boolean;
message: string;
};
export function done(message: string): Result {
return { ok: true, message };
}
Assert tests
Cover every helper with strictEqual assertions from node:assert. Pin the slug output, the result flag, and one edge case such as an empty title.
For runner based suites, read mocha testing background after these asserts pass. Start with assert, then graduate to a runner when the suite earns it.
// slug and done from above
import assert from "node:assert";
assert.strictEqual(slug("Hello World"), "hello-world");
assert.strictEqual(done("ok").ok, true);
console.log("utils tests pass");
Next: Modern TypeScript tour
Article author: Arthur Isaev