Sharing a Course Between Directions

The members’ note now comes out right, so the next part of Ruth’s script to port is the course picker. On a racing morning, the wind direction picks one of three courses. Ruth decides with a second match, where some cases cover several directions and a last case catches the rest.

A JavaScript case holds one value, so you need another way to say “either of these.” You’ll share one body between cases, give the leftover directions a fallback, and see when JavaScript developers look the answer up instead.

Stack Cases That Share a Course

Ruth’s match lists every direction that gets the same course in one case, joined with |:

Language: Python
direction = "NE"
match direction:
    case "N" | "NE":
        course = "harbour triangle"
    case "S" | "SW" | "W":
        course = "outer trapezoid"
    case _:
        course = "short windward-leeward"
print(course)

On the main morning, the wind is from the northeast, so the script prints harbour triangle.

A JavaScript case doesn’t close off a block. It marks where execution starts, and execution runs on until a break. Fall-through broke the members’ note, but here it does the work you want. A case with no body falls into the next one, so directions that share a course become stacked cases, one label per line, above one body and one break:

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.