This program assigns random sporting events to participants and calculates the number of days they need to train for their event. It demonstrates how to work with arrays, objects, and functions in JavaScript, while providing clear, readable output for each athlete.
-
Arrays and Objects
- The list of events is stored in an array, and the corresponding training days are stored in an object. This allows quick mapping from event to required training days.
-
Random Selection
- A function selects a random event for each participant using
Math.random()andMath.floor(). This introduces unpredictability and simulates a real-life scenario where athletes are assigned events randomly.
- A function selects a random event for each participant using
-
Function Decomposition
- Separate functions are used for:
- Selecting a random event
- Retrieving the training days for a given event
- Logging the athlete’s event
- Logging the athlete’s training duration
- This modular approach makes the code easier to read, maintain, and extend.
- Separate functions are used for:
-
Default Handling
- When retrieving training days, the code includes a default of 0 days if an unknown event is passed. This prevents errors from unexpected input.
-
Readable Output
- Output messages are user-friendly and clearly indicate the athlete’s assigned event and required training time.
- A blank line separates each participant’s information for clarity.
- Event: Triathlon
- Training Time: 100 days
- Message:
“Nala’s event is: Triathlon”
“Nala’s time to train is: 100 days”
- Event: Pentathlon
- Training Time: 200 days
- Message:
“Warren’s event is: Pentathlon”
“Warren’s time to train is: 200 days”
Note: The actual events are randomly selected, so outputs will vary each time the program runs.
This programme demonstrates practical use of arrays, objects, and functions to manage and display information. It shows how to combine randomisation with structured data to create dynamic, readable output and can easily be extended for more athletes or events. The modular design ensures the code is maintainable and easy to update.