Hand a list a rule as an arrow function and let a method do the loop: map makes a new list, filter keeps some items, find gives back the first match or undefined, and some and every answer yes or no, stopping as soon as they know. See why find needs a check, why the new list must be kept, and make TaskKit refuse a task that is already on the list.
TypeScript
Fundamentals
`map`, `filter`, `find`, `some`, and `every`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
At the end of the last lesson TaskKit walked its list with a loop.
Now look at the loops you would write next. One makes a new list of
every task in capitals. One keeps only the calls. One looks for the
first call, one asks whether rent is anywhere on the list, one
checks that every task is short. Each starts with an empty list or
a box, then a for...of, then an if or a push inside. Read them
side by side and they are nearly the same loop. Only the job in the
middle changes.
Think of a conveyor belt in a factory. The boxes ride past a single
station, and the worker there does one thing to each box: paints
it, or lifts the broken ones off, or stops the belt at the first
box with a red label. The belt is always the same; only the job at
the station changes. By the end of this lesson you hand a list a
rule in one line, and pick the method that does the job: a new
list, some of the items, one item, or a yes-or-no answer. TaskKit
uses one of them to refuse a task that is already on the list.
The same loop, five times
Here is the first of those loops: a new list with every task in
capitals. You can write it with what Module 4 has taught so far:
It works, and most of it is the same in every loop of this kind:
make an empty list, go through the items, push something. The one
piece that says what you actually want is task.toUpperCase().
Keeping only the calls would need an if around the push;
finding the first call would need a box for the answer and an if
that fills it only once.
These jobs come up so often that every list comes with a method
for each of them. You met methods in Module 2 as the commands a
string carries with it, task.trim() and task.toUpperCase(), and
push in lesson 4.1 is one that lists carry. The five in this
lesson do the looping for you. All you hand them is the one line
in the middle: what to do with each item.
A rule for every item: the arrow function
That one line has to be handed over as a value, the way you hand
console.log a string. You write it like this:
ts
(task) => task.toUpperCase()
Read it out loud: "a task goes to task.toUpperCase()". On the
left of the arrow, in parentheses, is a name for one item, the way
task was the name for one item in for (const task of tasks).
On the right is what to give back for that item. The whole thing
is an arrow function, named after its =>: a small rule that
takes one item and gives back an answer.
The method runs your rule on the items, one at a time and in order,
and does something with each answer. Which something depends on the method,
and that is the rest of this lesson.
You never write the type of task here. TypeScript knows that
tasks is a string[], so each item is a string, and it gives
task that type, the way Module 2's inference gave a box the type
of its value. Hover over task inside the rule in VS Code (Visual
Studio Code, your editor) and it
says (parameter) task: string: parameter is the word for the
name on the left of the arrow, and Module 5 says more about it.
That is why task.toUpperCase() is allowed: TypeScript checks the
rule against a string.
map and filter: a new list from the old one
map gives back a new list with the rule's answer for every item,
in the same order: the loop above in one line. filter asks the
rule a yes-or-no question about every item and gives back a new
list of only the items it answered true to. Its rule gives back
true or false.
Here are both on a conveyor belt. Choose map or filter on the
switch, then press Next to send the tasks through one at a
time, or let it play:
tasks
"buy milk"
"call mom"
"pay rent"
"call dad"
.map((task) => task.toUpperCase())"buy milk"→gives"BUY MILK""call mom"→gives"CALL MOM""pay rent"→gives"PAY RENT""call dad"→gives"CALL DAD"One item at a time
loud
"BUY MILK"
"CALL MOM"
"PAY RENT"
"CALL DAD"
Every item passes the rule once, in order
All 6 steps shown.Step 1 of 6: tasks.map((task) => task.toUpperCase())Step 2 of 6: "buy milk" → "BUY MILK"Step 3 of 6: "call mom" → "CALL MOM"Step 4 of 6: "pay rent" → "PAY RENT"Step 5 of 6: "call dad" → "CALL DAD"Step 6 of 6: loud = ["BUY MILK", "CALL MOM", "PAY RENT", "CALL DAD"]
All 6 steps shown.
tasks
"buy milk"
"call mom"
"pay rent"
"call dad"
.filter((task) => task.startsWith("call"))"buy milk"→givesfalse: left out"call mom"→givestrue: kept"pay rent"→givesfalse: left out"call dad"→givestrue: keptOne item at a time
calls
"call mom"
"call dad"
Left out
"buy milk"
"pay rent"
Every item passes the rule once, in order
All 6 steps shown.Step 1 of 6: tasks.filter((task) => task.startsWith("call"))Step 2 of 6: "buy milk" → false: left outStep 3 of 6: "call mom" → true: keptStep 4 of 6: "pay rent" → false: left outStep 5 of 6: "call dad" → true: keptStep 6 of 6: calls = ["call mom", "call dad"]
All 6 steps shown.
Three things in that walk are worth saying out loud:
Every item reaches the station, once, in order. Neither
method skips an item or stops early.
map keeps the length, filter may not. Four tasks go into
map and four come out. filter keeps the two calls.
tasks never changes. Both give back a new list, and the
belt still holds all four tasks when the walk ends.
Now run them yourself. Press Step to watch the rule's line run
once for every task, or Run to see what they print:
lengths is [8, 8, 8, 8], since each task here happens to be 8
characters. TypeScript works the type out from the rule: hover over
lengths in VS Code and it shows const lengths: number[].
Because both methods give back a new list, the new list has to go
somewhere. It is lesson 2.4's rule for trim(), applied to lists.
Bad — filter makes the list of
calls, and nothing keeps it.
The first prints all four tasks. Neither TypeScript nor Node says a
word, because throwing an answer away is allowed; the program just
does not do what you meant. Whenever you use map or filter,
keep what it gives back in a box.
find, some and every: they stop early
The other three give back one thing instead of a list, and they
stop as soon as they know it.
find gives back the first item the rule says true to, and
stops there.
some answers "is it true for at least one item?" It stops at
the first true and gives back true; if no item passes, it
gives back false.
every answers "is it true for all of them?" It stops at the
first false and gives back false; if every item passes, it
gives back true.
The belt shows where each one stops. The items it never reaches
are drawn dashed. Choose a method on the switch and press Next:
tasks
"buy milk"
"call mom"
"pay rent": never reached
"call dad": never reached
.find((task) => task.startsWith("call"))"buy milk"→givesfalse"call mom"→givestrue: found, stops"pay rent"→givesfalse"call dad"→givestrueOne item at a time
firstCall
"call mom"
find and some stop at the first true, every at the first false
All 4 steps shown.Step 1 of 4: tasks.find((task) => task.startsWith("call"))Step 2 of 4: "buy milk" → falseStep 3 of 4: "call mom" → true: found, stopsStep 4 of 4: firstCall = "call mom"
All 4 steps shown.
tasks
"buy milk"
"call mom"
"pay rent"
"call dad": never reached
.some((task) => task.includes("rent"))"buy milk"→givesfalse"call mom"→givesfalse"pay rent"→givestrue: stops"call dad"→givesfalseOne item at a time
rentDue
true
find and some stop at the first true, every at the first false
All 5 steps shown.Step 1 of 5: tasks.some((task) => task.includes("rent"))Step 2 of 5: "buy milk" → falseStep 3 of 5: "call mom" → falseStep 4 of 5: "pay rent" → true: stopsStep 5 of 5: rentDue = true
All 5 steps shown.
tasks
"buy milk"
"call mom"
"pay rent"
"call dad"
.every((task) => task.length < 10)"buy milk"→givestrue"call mom"→givestrue"pay rent"→givestrue"call dad"→givestrueOne item at a time
allShort
true
find and some stop at the first true, every at the first false
All 6 steps shown.Step 1 of 6: tasks.every((task) => task.length < 10)Step 2 of 6: "buy milk" → trueStep 3 of 6: "call mom" → trueStep 4 of 6: "pay rent" → trueStep 5 of 6: "call dad" → trueStep 6 of 6: allShort = true
All 6 steps shown.
find never looks at "call dad": it already has its answer at
"call mom". every looks at all four, because no task gives back
false, so it never has a reason to stop early. Run the three:
It prints call mom, true and true. some and every always
give back a boolean. find is different, because it can come
back empty-handed: when no item passes, it gives back undefined.
What find gives back: string | undefined
So TypeScript gives firstCall the type string | undefined, the
same type as process.argv.at(3) in Module 3 (argv, short for
argument vector, the list of words you typed), and for the same
reason: the value you want may not be there. The check that made
typedTask safe in lesson 3.5 makes firstCall safe too, the if
you already know:
Press Edit, change "call" to "walk" in the rule, and run it
again: no task starts with walk, find gives back undefined,
and the else road prints No calls today.
TaskKit refuses a task twice
Now TaskKit's step for this lesson. Today
node index.ts add "buy milk" "Buy milk" adds the same task twice.
Before add keeps a task, it should look for one that is already
on the list, ignoring capitals: a job for find. It is find
rather than some because TaskKit says which task was already
there, and some would only answer yes or no.
Open index.ts in ~/projects/taskkit. In the add case, look
for a twin right after newTask is made, and refuse it before the
room check:
index.tsts
const newTask = tidyTask.slice(0, 1).toUpperCase() + tidyTask.slice(1); const twin = tasks.find( (task) => task.toLowerCase() === newTask.toLowerCase() ); if (tidyTask === "") { console.log("Skipped an empty task"); } else if (twin !== undefined) { console.log("Already on the list:", twin); } else if (tasks.length < limit) {
newTask already starts with a capital, so typed buy milk and
Buy milk both become Buy milk. Comparing both in lower case also
catches BUY MILK or bUY mILK. find gives back undefined when
no task matches, so the else if refuses the new task only when
twin holds one, and the tasks after a refused one still go
through the loop. Check the file with tsc
(the TypeScript compiler, which npx starts) and run it with a
task typed twice:
npx tsc prints nothing: the file passes. Then TaskKit prints:
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Added: Buy milkAdded: Call momAlready on the list: Buy milkTasks added: 2 of 5, room for 3 moreList 40% fullYour list:1. Buy milk2. Call mom
Predict before you run
Follow find along the list and decide where it stops.
The broken file even works when you run it with Node: there
is a call on this list, so it prints CALL MOM. That is what makes
the mistake easy to miss. The day the list holds no call, find
gives back undefined and the same line stops the program with
TypeError: Cannot read properties of undefined (reading 'toUpperCase'). TypeScript is warning you about that day. Whenever
you see possibly 'undefined' on a box that came from find, the
fix is an if that checks for undefined, not swapping find for
another method.
TypeScript refuses this program. There is no rent on this list, so
find gives back undefined. Fix it so it prints
No rent this month, and would print the rent task in capitals if
there were one.
Loading the editor…
Exercise · Write the code
Keep the long tasks
Your tasks take 25, 15, 30 and 10 minutes. Use filter to make
long, a list of the ones over 20 minutes, then print how many
there are. The program prints 2.
tasks.map((task) => task.length): what comes back?
Check yourself
What type does tasks.find(...) give back for a string[]?
Check yourself
Is rent anywhere on the list? Which method answers?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
map, filter, find, some, and every
What things are
Word
What it means
Method
A command a value carries with it: tasks.map(…)
Arrow function
A rule written (task) => …: an item in, an answer out
Function
Code you can hand around and run later; Module 5
Parameter
The name on the left of the arrow: task
Code
Write
To
.map((task) => …)
Make a new list of the rule's answers
.filter((task) => …)
Keep the items the rule says true to
.find((task) => …)
Get the first item that passes, or undefined
.some((task) => …)
Ask whether at least one item passes
.every((task) => …)
Ask whether all the items pass
Rules
Rule
What it means
Keep the answer
tasks never changes; put the new list in a box
filter wants a yes
Its rule gives back true or false
find may miss
On a string[], string | undefined; check it first
Stops early
find, some at the first true; every at a false
No types to write
TypeScript gives task the type of the list's items
Where to go next
You can now hand a list a rule as an arrow function, make a new
list with map, keep some items with filter, find one with
find, and answer a yes-or-no question with some or every, and
you know that find needs a check before its answer is used.
TaskKit refuses a task that is already on its list.
Next is Sorting and its pitfalls. A list of tasks is more
useful in order, and sort takes a rule much like the ones here.
Unlike the five methods in this lesson, it changes the list you
call it on, and that is the first of its pitfalls.
Before you move on, run node index.ts add "buy milk" "BUY MILK"
and read why the second is refused. Then, in index.ts, change
find to some, run npx tsc --noEmit--types node index.ts
(it passes), then run node index.ts add "buy milk" again: TaskKit
now refuses even the first task. Work out why from what some
gives back, then put find back.