Nadia’s booking confirmations need a caretaker’s notice for each event. Parties and weddings share the music deadline, while classes and meetings need their rooms ready early. Ana Silva’s market needs a notice too, even though it has no special rule yet.
You can express those choices with a switch, but each branch here computes a message from the request. A lookup of functions lets you keep the messages together. For the five example requests below, you’ll call the matching function when one exists and keep the fallback for Ana’s market. Start with how the Python script makes that choice.
Keep a Function Per Kind
In Python, a dictionary can hold functions as values. Nadia’s script looks up the handler before calling it, so an unlisted kind reaches the fallback. These snippets keep only the request fields the notices use:
def music_off(r):
return "music off by 11 p.m."
def set_up_early(r):
if len(r["rooms"]) == 1:
return f"{r['rooms'][0]} set up 15 minutes early"
return "rooms set up 15 minutes early"
NOTICES = {
"wedding": music_off,
"party": music_off,
"class": set_up_early,
"meeting": set_up_early,
}
def notice_for(r):
handler = NOTICES.get(r["kind"])
if handler is not None:
return handler(r)
return f"check the {r['kind']} request by hand"
print(notice_for({"kind": "class", "rooms": ["hall"]}))
print(notice_for({"kind": "party", "rooms": []}))
print(notice_for({"kind": "wedding", "rooms": ["hall", "kitchen"]}))
print(notice_for({"kind": "class", "rooms": ["studio"]}))
print(notice_for({"kind": "market", "rooms": ["hall"]}))
The Python script prints the notices for the choir, Maya, Tom, the yoga class, and Ana, in order:
hall set up 15 minutes early
music off by 11 p.m.
music off by 11 p.m.
studio set up 15 minutes early
check the market request by hand
In JavaScript, a lookup object holds values under keys you write in the code, and bracket notation retrieves the value associated with the key in r.kind. Arrow functions use => to separate their parameters from their bodies. The conditional operator chooses the room-specific message when .length === 1.