Spotting Remote Postcodes With String Keys

Order 1042’s tags are clean now, and the next line of Marta’s Python script deals with money. Her courier adds a £4.50 surcharge for parcels going to Shetland and the Outer Hebrides. Order 1043 is going to Sam Tait at 4 Harbour Street, Lerwick, postcode ZE1 0AA, which is in Shetland. If the port misses that, Marta pays the surcharge out of her own pocket.

The Python script spots remote addresses with a set of pairs, a habit that doesn’t port the way it looks. In this lesson, you’ll see why a Set can’t find a pair you give it, and you’ll build the key a JavaScript developer would use instead. Start with the Python check that works.

Port the Set of Pairs

The courier names its remote areas by country and by postcode area, the letters at the start of a postcode. Shetland is ZE and the Outer Hebrides are HS. Both have two letters, so the first two characters of a postcode are enough to spot them. The Python script stores each area as a tuple of country and area, and the set checks the pair for order 1043’s address with in:

Language: Python
REMOTE_AREAS = {("GB", "ZE"), ("GB", "HS")}
REMOTE_SURCHARGE = 4.50

address = {"city": "Lerwick", "postcode": "ZE1 0AA", "country": "GB"}
area = address["postcode"][:2]
print((address["country"], area) in REMOTE_AREAS)

That prints True. On its own, this line only checks the address, and in the script the result decides whether the surcharge goes on. Order 1043 has no shipping address of its own, so address here is its billing address, cut down to its city, postcode, and country.

JavaScript has no tuple type. When you need a small fixed group of values, you write a short array, such as ["GB", "ZE"], and treat it like a tuple. A Set takes any iterable, as you saw with the tags, so the port builds one from an array of these pairs and calls .has(), its equivalent of in. Before you run it, predict what it logs:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.