Same day delivery
was a small launch.
Four postcode areas
near the depot.
const sameDay = ["LS", "BD", "HX", "WF"];
if (sameDay.indexOf(area)) {
offerSameDay();
}
It went live on a Monday.
By Wednesday
a customer in Glasgow
had been promised
a delivery by six.
So had Cardiff.
So had Truro.
And the customers in Leeds,
two miles from the depot,
were never offered it at all.
Here is the mechanism.
indexOf does not answer
yes or no.
It answers where.
Zero
if the item is first.
One, two, three
further down.
Minus one
if it is not there.
Then the if statement
turns that number
into true or false.
Zero is false.
Every other number,
minus one included,
is true.
So the check
failed for the first area in the list
and passed
for every area in the country
that was not in the list at all.
Nobody noticed in review.
The line reads
exactly like English.
If the area is in the list.
Nobody tested Leeds,
because Leeds
was obviously fine.
Nobody tested Glasgow,
because Glasgow
was obviously out.
The two cases
everyone was sure about
were the two
the code got wrong.
Python has the same trap.
str.find returns minus one
when it finds nothing.
Ask the question
you actually mean:
if (sameDay.includes(area)) {
offerSameDay();
}
includes has been in JavaScript
since 2016.
It returns a real true
or a real false.
In Python,
use in.
If you are stuck with indexOf,
write the comparison out:
if (sameDay.indexOf(area) !== -1)
In TypeScript,
the strict-boolean-expressions rule
from typescript-eslint
will refuse a number in a condition
once you turn its allowNumber option off.
And test the edges
of every list check.
The first item.
The last item.
Something that is not there.
Three tests.
One of them
would have found this
before Glasgow did.
A function that returns a position
is not answering your question.
It is answering
a different one,
very precisely.
– Serguey Asael Shinder