Breaking a problem into small functions, starting from plain-language steps
Turn a problem said in one sentence into plain-language steps, write each step as a line or a small function that answers or does a job, and call them in order from a main function that reads like the plan. TaskKit’s banner and summary become functions of their own.
Fundamentals
TypeScript
Breaking a problem into small functions, starting from plain-language steps. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
TaskKit has five functions now, and each name says what it does:
capitalize, percentFull, alphabetical, sameTask,
printList. Each one was pulled out of code that already worked.
Now a new wish arrives, in one sentence: at the end of the day,
show me how it went. You know exactly what you want to see. What
you do not know is the first line to type, because a sentence is
not a list of lines.
Your grandmother's drawer has an answer for that too. The card for
Sunday lunch is short. It does not explain how to make pastry; it
says Make the pastry (see the pastry card), then Fill the pie,
then Bake for forty minutes. A big recipe is a short list of
steps, and every step that needs explaining has a card of its own.
In this lesson you work the same way: you write the problem as a
few plain steps, turn each step into a line or a small function,
and write one function that follows the list. By the end, the
end-of-day report will run, and the last lines of TaskKit will
read like its plan.
Say it in plain words first
Here is the wish in full: at the end of the day, show how many
tasks are done out of all of them, as a percent, with a word of
encouragement, and then the tasks still left. Every part of it is
clear, and none of it is code yet. Before you write any TypeScript,
write the sentence again as a list of short steps, one thing each,
in the order they have to happen. Put them in the file as
comments, the // lines of lesson 2.7 that the computer skips:
day.tsts
// At the end of the day:// 1. Count all the tasks// 2. Work out the percent done// 3. Print how many are done// 4. Pick a message and print it// 5. List the tasks still left
These are plain-language steps: what the program does, in your
own words, before you decide how. Programmers also call them
pseudocode, "almost code". They are cheap to change. Moving a
step or splitting one costs a keystroke here, and a rewrite once
the code exists.
Each step should be one job you could do with nothing else in your
head. Read step 4 again: Pick a message and print it. That "and"
joins two jobs, finding the right words and showing them, and it
decides what the step becomes. It stays one numbered step only
because its second half, printing, is a single line. Here is what
every step becomes, decided before any body is written:
1
Count all the tasks
Stays a line: done.length + left.length already says it.
2
Work out the percent done
A function that answers a number:
percentDone(part: number, whole: number): number.
3
Print how many are done
Stays a line: one console.log with a template string.
4
Pick a message and print it
Two jobs, two parts: cheer(percent: number): string picks it,
and a console.log prints it.
5
List the tasks still left
A function that does a job:
printLeft(left: string[]): void.
Each step becomes a line, or a function that answers or does
One rule decides every step in the figure. A step that answers a
question becomes a function that gives its answer back, as in lesson
5.1. A step that only does a job becomes a void function, as in
lesson 5.6. A step that is already one clear line needs no name of its
own.
Write the main function first
Start from the top, not from the steps, so you find out what each step
must take and give back before you write it. The main function is
the one that runs the whole plan: it calls the steps in order and
hands each one what it needs. Write it as if every step already
existed, one line under each comment, and call each step by the name
its words suggest:
Run it. TypeScript refuses it with three errors:
Cannot find name 'percentDone'. on line 5, then the same for
'cheer' on line 9 and 'printLeft' on line 11. That is lesson 5.5's
message for a name that means nothing where it is used, and here it is
welcome. It is the list of functions still to write, made by
TypeScript from your own plan. Node, running the file on its own,
would stop at the first one with
ReferenceError: percentDone is not defined and tell you nothing
about the other two.
Look at what the main function already says. You can read it
without knowing how the percent is worked out or how a message is
picked: those are the steps' business, not its own.
Each step answers or does
Now write the three missing functions, one at a time, each from its
step. Two questions give you its first line. What does it need?
That becomes its parameters. What does it give back? That becomes
its return type, or void when it gives nothing back.
Work out the percent done needs two numbers, how many tasks are
done and how many there are in all, and answers with a number:
Its body is the one in TaskKit's percentFull. Only the names
changed, to fit the new job: a part out of a whole.
Pick a message needs only the percent, and answers with text. It
does not print, because printing is the other half of step 4, and
that half stays in the main function:
The first return ends the call, as in lesson 5.1, so the last
line is reached only when the percent is under 50.
List the tasks still left needs the list, and does a job: it
prints. It gives nothing back, so its return type is void:
The comments in endOfDay have done their job. Each one now says
what the name under it already says, which is the comment lesson
2.7 called one that tells the reader nothing new. Delete them, and
put the three steps above the main function. The whole file is in
the next section, where you run it.
The main function reads like the plan
endOfDay is five lines long, and each line is a step of the plan.
Here is what happens when it runs. Press Next step to follow
it, or Play:
The sixth step of the player, where cheer gets 67, is the one to
look at. 67 was the answer of percentDone. endOfDay kept it in its
box percent and handed it on to cheer. The steps never talk to
each other: every answer comes back to the main function, and the main
function hands it on. That is why each step can be written, read and
fixed on its own.
Here is the same program to run yourself. Press Run, and it prints
2 of 3 done (67%), More than half done, Still to do: and
- pay rent. Then press Step: the Call stack column shows
which function the computer is inside,
global › endOfDay › percentDone while the percent is worked out, and
global › endOfDay again between the steps.
How small is a step
There is no line count for a step. There are three questions.
Can you name it without "and"?cheer picks a message. If it
printed the message too, its honest name would be cheerAndPrint,
and the day you want the words somewhere else, such as in a
TaskKit summary, you could not have them without the printing.
Does it take what it needs? Lesson 5.5 showed that a function
can read the boxes around it. A step that does that works only for
those boxes.
Bad — printLeft reads the
file's own left, so there is no way to hand it tomorrow's list.
Good — printLeft takes the
list as a parameter, so it prints whichever list it is handed.
The first version is right today and useless tomorrow: to print
another list, you would copy the whole function and change one
name, which is the copying lesson 5.1's card saved you from.
Is it already one clear line?done.length + left.length says
what it does as well as a name would. A function called countAll
would be one more name to learn, and it would save nothing. Give a
step a name when its lines need one.
Steps of that size give you a program you read from the top down:
endOfDay
The plan: one line for every step, in order
percentDone · cheer · printLeft
The steps: one job each, a few lines long
Math.round · console.log · forEach
What JavaScript gives you: you never read inside
Read from the top: each level says what, the next says how
You have never read the inside of Math.round, and you never needed
to: its name and the number it gives back were enough. A step with a
good name earns the same trust.
TaskKit's last lines read like its plan
Now TaskKit's step for this lesson: give it the same shape. Say in
four plain steps what index.ts in ~/projects/taskkit does when
it runs: print the banner, add the tasks, print how full the list
is, print the list from A to Z. The last step is printList
already. Two of the others are still loose lines, and each becomes
a function that does a job. Adding the tasks stays as it is in this
lesson: it is the loop that reads what you typed, and it already
calls capitalize and sameTask for its hard parts.
At the top of the file, under printList, declare both. If your
banner prints TASKKIT 0.1, put your line in printBanner in place
of console.log("TaskKit", version);, and if you wrote roomLeft
in lesson 5.1, keep your line for room:
Then replace the banner's lines under const version = "0.1"; with
a call:
and, near the end, the lines that print how full the list is:
Check the file with tsc (the TypeScript compiler, which npx
starts) and run it:
npx tsc prints nothing: the file passes. Then TaskKit prints:
The output is exactly what it was, and the file's last two lines,
printSummary(tasks.length, limit); and printList(tasks);, read
like the end of its plan.
Predict before you run
The same steps, on a harder day. Work out each step's answer, and
remember at which percent cheer changes its message.
Predict
What is the second line this program prints?
The common mistake: a box left inside a step
When you move lines that already work into a function of their own,
the boxes those lines make move with them. The line that used the
box stays behind.
Common mistake
Using a box that now lives inside another function
Say you had first written the percent line straight into
endOfDay, and then moved it into a step of its own as it was:
npx tsc --noEmit--types node day.ts refuses it:
TS2304 is the number of this message: TS for TypeScript.
Cannot find name 'percent'.
The fix
Make the step give its answer back, and keep that answer in a box
where it is used:
It prints 2 of 3 done (67%).
The box percent was made inside percentDone's braces, and, as
lesson 5.5 showed, it ends at their }. Run it anyway, and Node
stops on line 7 with ReferenceError: percent is not defined. So when
Cannot find name names a box rather than a function, ask where
that box is made. If it is inside another function, that function
has to give it back with return, and the caller keeps the answer
in a box of its own.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each one runs in your browser. Press Check when you think you
have it; if you are stuck, the hints come one at a time.
Recap
Recap · 3 questions
Check yourself
What do you write before any code?
Check yourself
How does one step's answer reach the next step?
Check yourself
A step's name needs an 'and'. What does that tell you?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Breaking a problem into small functions
What things are
Word
What it means
Plain-language steps
What the program does, in words, before any code
Pseudocode
Another name for plain-language steps
Main function
The function that runs the plan, step by step
A step that answers
A function with a return type, like percentDone
A step that does
A void function, like printLeft
Code
Write
To
// Count all the tasks
Write a step as a comment first
percentDone(2, 3)
Call a step with what it needs
cheer(percent)
Hand one step's answer on to the next
endOfDay(done, left)
Run the whole plan
Rules
Rule
What it means
One job
A step whose name needs "and" is two steps
Needs in, answer out
Parameters in, return out; no outside boxes
A clear line
Stays a line; it needs no name
Main function first
TS2304 lists the steps still to write
Plan comments
Delete them once the names say the same
A box inside a step
TS2304 outside it: return it instead
Wrong value handed to a step
TS2345: read the step's first line
Where to go next
You can now take a problem said in one sentence, write it as plain
steps, and turn each step into a line, a function that answers, or
a function that does a job. You can write the main function first
and let TypeScript list what is missing, and you know that every
answer travels back through the main function on its way to the
next step.
Next is The call stack: what happens when functions call
functions. In this lesson endOfDay called percentDone, and
the computer came back to the right line every time. There you see
how it keeps track of where to come back to, one call inside
another.
Before you move on, read TaskKit's index.ts the way this lesson
reads endOfDay: from printBanner(version); down, say which of the
four plain steps each part carries out. Then, in VS Code (Visual
Studio Code, your editor), rest the pointer on printSummary where it
is called, and check that its first line tells you what to hand it,
without your opening the body.
Exercise · Read the code
Choose the first line for a step
The plan says Pick a message for the percent, and the main function
prints what the step gives back: console.log(cheer(percent));. Which
first line fits that step?
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Added: Pay rentAdded: Call MomAdded: Buy milkTasks added: 3 of 5, room for 2 moreList 60% fullYour list, A to Z:1. Buy milk2. Call Mom3. Pay rent
Outputtext
day.ts:7:49 - error TS2304: Cannot find name 'percent'.7 console.log(`${done.length} of ${all} done (${percent}%)`); ~~~~~~~Found 1 error in day.ts:7
day.tsts
function endOfDay(done: string[], left: string[]): void { // 1. Count all the tasks const all = done.length + left.length; // 2. Work out the percent done const percent = percentDone(done.length, all); // 3. Print how many are done console.log(`${done.length} of ${all} done (${percent}%)`); // 4. Pick a message and print it console.log(cheer(percent)); // 5. List the tasks still left printLeft(left);}endOfDay(["buy milk", "call mom"], ["pay rent"]);
ts
function percentDone(part: number, whole: number): number { return Math.round((part / whole) * 100);}
ts
function cheer(percent: number): string { if (percent >= 50) { return "More than half done"; } return "Every task counts";}
ts
function printLeft(left: string[]): void { console.log("Still to do:"); left.forEach((task) => console.log(`- ${task}`));}
const left = ["pay rent"];const tomorrow = ["walk the dog"];function printLeft(): void { console.log("Still to do:"); left.forEach((task) => console.log(`- ${task}`));}printLeft();
ts
const left = ["pay rent"];const tomorrow = ["walk the dog"];function printLeft(tasks: string[]): void { console.log("Still to do:"); tasks.forEach((task) => console.log(`- ${task}`));}printLeft(tomorrow);
index.tsts
function printBanner(version: string): void { const divider = "=".repeat(28); console.log(divider); console.log("TaskKit", version); console.log("Your tasks, in your terminal"); console.log(divider);}function printSummary(added: number, limit: number): void { const room = limit - added; console.log( `Tasks added: ${added} of ${limit}, room for ${room} more` ); const percent = percentFull(added, limit); console.log(`List ${percent}% full`);}
index.tsts
const version = "0.1";const divider = "=".repeat(28);console.log(divider);console.log("TaskKit", version);console.log("Your tasks, in your terminal");console.log(divider);printBanner(version);
forEach prints one line for every task left. printLeft gives
nothing back.
Prints - pay rent
Line 20.all = 3, percent = 67. Inside endOfDay.
The closing brace: every line of the plan has run, in its
order.
Line 21.
Back on line 21. endOfDay gave nothing back, and the program is
over.
endOfDay runs the plan, and each function's answer comes back
Exercise · Fix the error
Hand the step what it asks for
TypeScript refuses this program with Argument of type 'string[]' is not assignable to parameter of type 'number'. Change the call
on the last line, and nothing else, so that it prints 67% done.
Loading the editor…
Exercise · Fix the error
Split the step that prints
cheerAndPrint picks a message and prints it, so the summary line
cannot have its words: it prints Summary: undefined. Turn it into
cheer(percent: number): string, which gives the message back, and
print in the callers. The program should print More than half done
and then Summary: Every task counts.
Loading the editor…
Exercise · Write the code
Write the missing step
The plan and the main function are written. TypeScript says
Cannot find name 'shortest'. Write shortest: it takes a list of
tasks and gives back the one with the fewest characters. Write the
types of its parameter and of what it gives back.