Terminology (5)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Composition
- Connecting functions so the result of one is the argument of the next.
- Pipeline
- A sequence of steps applied in order, each taking the previous result.
- In place
- Writing into existing storage. A function can change that storage and also return a result.
- Shallow copy
- A new container holding the same elements; objects or pointers inside are shared.
- Deep copy
- A copy that duplicates the relevant nested state to the depth its independence contract requires; ordinary container copying alone does not establish that.
Connect an output to the next input
Function composition builds behavior by feeding one function’s result into another. If first maps A to B and second maps B to C, their composition maps A to C. A pipe helper commonly reads in execution order, but its body determines the actual order.
Building the composed function and running it are separate actions. Type-compatible steps can still differ in meaning or mutate shared input, so trace the data as well as the types. A preview that preserves its source needs every writing step to respect the source’s retained storage.
01Direction
A composition helper’s body decides which step runs first
A request moderator previews a song catalog without editing the arrival queue. The supplied display policy removes an exact leading The plus a space, then keeps six Unicode scalar values without normalizing the name. Ranking and a one-vote promotion preview are derived views: refresh or undo must still see the original request order and recorded votes.
The reduced ASCII probe removes an optional leading The before limiting the label to six characters. pipe connects the two supplied steps in different orders. Trace which text reaches each step, then predict both labels.
function pipe<A, B, C>(first: (a: A) => B, second: (b: B) => C): (a: A) => C {
return (a) => second(first(a));
}
const stripThe = (name: string) => (name.startsWith("The ") ? name.slice(4) : name);
const shorten = (name: string) => name.slice(0, 6);
const stripFirst = pipe(stripThe, shorten);
const shortenFirst = pipe(shorten, stripThe);
console.log(`[${stripFirst("The Beatles")}] [${shortenFirst("The Beatles")}]`);
npx tsc --noEmit --strict --target ES2022 --module nodenext main.ts && node main.ts
Use the selected language’s command. These literal probes use ASCII names and flat numeric or string/number records. The supplied practice formatter defines its Unicode counting policy separately.
02When steps run
Factories can run while the returned steps wait for a call
The moderator can prepare a label formatter before a request arrives. Here each factory reports its setup, and its returned function reports each use. Predict which work happens before and after built.
function step(
name: string,
change: (text: string) => string
): (text: string) => string {
console.log(`made ${name}`);
return (text) => {
console.log(`ran ${name}`);
return change(text);
};
}
const upper = step("upper", (text) => text.toUpperCase());
const exclaim = step("exclaim", (text) => text + "!");
const shout = (text: string) => exclaim(upper(text));
console.log("built");
console.log(shout("encore"));
03Steps that change their input
Check which storage a sorting step receives
The next preview ranks requests, while refresh still needs arrival order. This reduced integer-score probe checks which storage a sorting call changes. Predict the printed values and trace where they came from.
function topTwo(scores: number[]): number[] {
return scores.sort((a, b) => b - a).slice(0, 2);
}
const scores = [3, 9, 5];
const top = topTwo(scores);
console.log(top.join(" "), "|", scores.join(" "));
04What a copy shares
Copying a list of records may still share the records
The promotion preview changes votes as well as order. Before handling the whole queue, inspect a one-request copy: does its vote field still belong to the original request? Predict both counts.
type Request = { song: string; votes: number };
const queue: Request[] = [{ song: "Jolene", votes: 2 }];
const copy = [...queue];
copy[0]!.votes += 1;
console.log(copy[0]!.votes, queue[0]!.votes, queue[0]!.song);
05Repair the moderator’s previews
Format labels, rank a view, then preview a promotion
First connect the display steps in policy order: strip the leading The before shortening and adding brackets. Then show the top two requests by votes while retaining the arrival queue for refresh. Finally preview a one-vote promotion for every request without recording those votes in the queue.
Each supplied caller prints the derived view and then the retained queue, so a refresh regression is visible. The promotion is a preview action; its votes have not been saved.
Repair the moderator’s previews
Step order, a step that reorders its input, then a copy that still shares.
In the frontend Derive a caption from a prop Optional
A moderator’s preview caption trims surrounding space for presentation and then adds brackets. These two scalar string steps return display text while the original prop remains available to the caller.
const trim = (text: string) => text.trim();
const frame = (text: string) => `[${text}]`;
const caption = (text: string) => frame(trim(text));
export default function Caption({ rawTitle }: { rawTitle: string }) {
return <p>{caption(rawTitle)}</p>;
}
caption calls trim first and passes its result to frame. These shown functions calculate text without writing state or assigning to the prop; composing functions alone would not guarantee that for arbitrary callbacks.
Sources: React: Keeping components pure,Svelte: Derived state.
Sources
Sign in to keep your read marks on every device. Sign in
Was this helpful?