javascript
exercises
exercises.js⚡javascript
/**
* =====================================================
* 4.2 SWITCH STATEMENTS - EXERCISES
* =====================================================
* Practice multi-way branching
*/
/**
* Exercise 1: Day of Week
*
* Return the name of the day given a number (1-7).
* 1 = Monday, 7 = Sunday
* Return "Invalid day" for other numbers.
*/
function getDayName(dayNum) {
// TODO: Use switch to return the day name
}
// Test cases:
console.log('Exercise 1:');
console.log(getDayName(1)); // "Monday"
console.log(getDayName(5)); // "Friday"
console.log(getDayName(7)); // "Sunday"
console.log(getDayName(0)); // "Invalid day"
/**
* Exercise 2: Month Days
*
* Return the number of days in a given month (1-12).
* Assume non-leap year (February has 28 days).
*/
function getDaysInMonth(month) {
// TODO: Use switch to return days in the month
}
// Test cases:
console.log('\nExercise 2:');
console.log(getDaysInMonth(1)); // 31
console.log(getDaysInMonth(2)); // 28
console.log(getDaysInMonth(4)); // 30
console.log(getDaysInMonth(13)); // "Invalid month"
/**
* Exercise 3: Grade Description
*
* Return a description for letter grades:
* A: "Excellent"
* B: "Good"
* C: "Average"
* D: "Below Average"
* F: "Failing"
*/
function getGradeDescription(grade) {
// TODO: Use switch (handle both upper and lower case)
}
// Test cases:
console.log('\nExercise 3:');
console.log(getGradeDescription('A')); // "Excellent"
console.log(getGradeDescription('b')); // "Good"
console.log(getGradeDescription('F')); // "Failing"
console.log(getGradeDescription('X')); // "Invalid grade"
/**
* Exercise 4: Calculator
*
* Perform a calculation based on the operator.
* Support: +, -, *, /, %
* Return null for invalid operators.
*/
function calculate(a, operator, b) {
// TODO: Use switch on the operator
}
// Test cases:
console.log('\nExercise 4:');
console.log(calculate(10, '+', 5)); // 15
console.log(calculate(10, '-', 5)); // 5
console.log(calculate(10, '*', 5)); // 50
console.log(calculate(10, '/', 5)); // 2
console.log(calculate(10, '%', 3)); // 1
console.log(calculate(10, '^', 2)); // null
/**
* Exercise 5: Month to Season
*
* Return the season for a given month number:
* 12, 1, 2 = "Winter"
* 3, 4, 5 = "Spring"
* 6, 7, 8 = "Summer"
* 9, 10, 11 = "Fall"
*/
function getSeason(month) {
// TODO: Use switch with grouped cases
}
// Test cases:
console.log('\nExercise 5:');
console.log(getSeason(1)); // "Winter"
console.log(getSeason(4)); // "Spring"
console.log(getSeason(7)); // "Summer"
console.log(getSeason(10)); // "Fall"
/**
* Exercise 6: HTTP Status Category
*
* Return the category of an HTTP status code:
* 1xx: "Informational"
* 2xx: "Success"
* 3xx: "Redirection"
* 4xx: "Client Error"
* 5xx: "Server Error"
*
* Hint: Use switch(true) or Math.floor(code/100)
*/
function getStatusCategory(code) {
// TODO: Return the category
}
// Test cases:
console.log('\nExercise 6:');
console.log(getStatusCategory(100)); // "Informational"
console.log(getStatusCategory(200)); // "Success"
console.log(getStatusCategory(301)); // "Redirection"
console.log(getStatusCategory(404)); // "Client Error"
console.log(getStatusCategory(500)); // "Server Error"
/**
* Exercise 7: Command Handler
*
* Handle commands for a simple todo app:
* "add": return "Adding item"
* "remove" or "delete": return "Removing item"
* "list" or "show" or "display": return "Showing items"
* "clear" or "reset": return "Clearing all items"
* default: return "Unknown command"
*/
function handleCommand(command) {
// TODO: Use switch with grouped cases
}
// Test cases:
console.log('\nExercise 7:');
console.log(handleCommand('add')); // "Adding item"
console.log(handleCommand('delete')); // "Removing item"
console.log(handleCommand('show')); // "Showing items"
console.log(handleCommand('reset')); // "Clearing all items"
console.log(handleCommand('help')); // "Unknown command"
/**
* Exercise 8: Medal Award
*
* Return the medal type for race positions:
* 1: "Gold Medal 🥇"
* 2: "Silver Medal 🥈"
* 3: "Bronze Medal 🥉"
* 4-10: "Top 10 Finish"
* 11+: "Participation Award"
*/
function getMedal(position) {
// TODO: Use switch (may need switch(true) for ranges)
}
// Test cases:
console.log('\nExercise 8:');
console.log(getMedal(1)); // "Gold Medal 🥇"
console.log(getMedal(2)); // "Silver Medal 🥈"
console.log(getMedal(3)); // "Bronze Medal 🥉"
console.log(getMedal(7)); // "Top 10 Finish"
console.log(getMedal(15)); // "Participation Award"
/**
* Exercise 9: Traffic Light
*
* Implement a traffic light state machine.
* Given current state and "next" event, return the next state.
*
* red -> "next" -> green
* green -> "next" -> yellow
* yellow -> "next" -> red
*
* Any state -> "reset" -> red
*/
function nextLightState(currentState, event) {
// TODO: Implement the state machine
}
// Test cases:
console.log('\nExercise 9:');
console.log(nextLightState('red', 'next')); // "green"
console.log(nextLightState('green', 'next')); // "yellow"
console.log(nextLightState('yellow', 'next')); // "red"
console.log(nextLightState('green', 'reset')); // "red"
console.log(nextLightState('red', 'invalid')); // "red" (no change)
/**
* Exercise 10: Vowel or Consonant
*
* Return "vowel" for a, e, i, o, u (case insensitive).
* Return "consonant" for other letters.
* Return "not a letter" for non-letters.
*/
function classifyLetter(char) {
// TODO: Check if it's a letter, then if vowel or consonant
}
// Test cases:
console.log('\nExercise 10:');
console.log(classifyLetter('a')); // "vowel"
console.log(classifyLetter('E')); // "vowel"
console.log(classifyLetter('b')); // "consonant"
console.log(classifyLetter('Z')); // "consonant"
console.log(classifyLetter('5')); // "not a letter"
console.log(classifyLetter('!')); // "not a letter"
// =====================================================
// BONUS CHALLENGES
// =====================================================
/**
* Bonus 1: Roman Numeral Converter
*
* Convert a single Roman numeral character to its value.
* I=1, V=5, X=10, L=50, C=100, D=500, M=1000
*/
function romanToNumber(numeral) {
// TODO: Use switch
}
console.log('\nBonus 1:');
console.log(romanToNumber('I')); // 1
console.log(romanToNumber('V')); // 5
console.log(romanToNumber('X')); // 10
console.log(romanToNumber('M')); // 1000
/**
* Bonus 2: Rock Paper Scissors Lizard Spock
*
* Extended rock-paper-scissors game.
* - Scissors cuts Paper
* - Paper covers Rock
* - Rock crushes Lizard
* - Lizard poisons Spock
* - Spock smashes Scissors
* - Scissors decapitates Lizard
* - Lizard eats Paper
* - Paper disproves Spock
* - Spock vaporizes Rock
* - Rock crushes Scissors
*
* Return "Player 1 wins", "Player 2 wins", or "Tie"
*/
function rpsls(player1, player2) {
// TODO: Use switch to determine winner
}
console.log('\nBonus 2:');
console.log(rpsls('rock', 'scissors')); // "Player 1 wins"
console.log(rpsls('spock', 'scissors')); // "Player 1 wins"
console.log(rpsls('lizard', 'spock')); // "Player 1 wins"
console.log(rpsls('paper', 'paper')); // "Tie"
// =====================================================
// SOLUTIONS (Uncomment to check your answers)
// =====================================================
/*
// Exercise 1 Solution:
function getDayName(dayNum) {
switch (dayNum) {
case 1: return "Monday";
case 2: return "Tuesday";
case 3: return "Wednesday";
case 4: return "Thursday";
case 5: return "Friday";
case 6: return "Saturday";
case 7: return "Sunday";
default: return "Invalid day";
}
}
// Exercise 2 Solution:
function getDaysInMonth(month) {
switch (month) {
case 1: case 3: case 5: case 7:
case 8: case 10: case 12:
return 31;
case 4: case 6: case 9: case 11:
return 30;
case 2:
return 28;
default:
return "Invalid month";
}
}
// Exercise 3 Solution:
function getGradeDescription(grade) {
switch (grade.toUpperCase()) {
case "A": return "Excellent";
case "B": return "Good";
case "C": return "Average";
case "D": return "Below Average";
case "F": return "Failing";
default: return "Invalid grade";
}
}
// Exercise 4 Solution:
function calculate(a, operator, b) {
switch (operator) {
case "+": return a + b;
case "-": return a - b;
case "*": return a * b;
case "/": return a / b;
case "%": return a % b;
default: return null;
}
}
// Exercise 5 Solution:
function getSeason(month) {
switch (month) {
case 12: case 1: case 2:
return "Winter";
case 3: case 4: case 5:
return "Spring";
case 6: case 7: case 8:
return "Summer";
case 9: case 10: case 11:
return "Fall";
default:
return "Invalid month";
}
}
// Exercise 6 Solution:
function getStatusCategory(code) {
switch (Math.floor(code / 100)) {
case 1: return "Informational";
case 2: return "Success";
case 3: return "Redirection";
case 4: return "Client Error";
case 5: return "Server Error";
default: return "Unknown";
}
}
// Exercise 7 Solution:
function handleCommand(command) {
switch (command.toLowerCase()) {
case "add":
return "Adding item";
case "remove":
case "delete":
return "Removing item";
case "list":
case "show":
case "display":
return "Showing items";
case "clear":
case "reset":
return "Clearing all items";
default:
return "Unknown command";
}
}
// Exercise 8 Solution:
function getMedal(position) {
switch (position) {
case 1:
return "Gold Medal 🥇";
case 2:
return "Silver Medal 🥈";
case 3:
return "Bronze Medal 🥉";
default:
switch (true) {
case position <= 10:
return "Top 10 Finish";
default:
return "Participation Award";
}
}
}
// Exercise 9 Solution:
function nextLightState(currentState, event) {
if (event === "reset") return "red";
switch (currentState) {
case "red":
return event === "next" ? "green" : "red";
case "green":
return event === "next" ? "yellow" : "green";
case "yellow":
return event === "next" ? "red" : "yellow";
default:
return "red";
}
}
// Exercise 10 Solution:
function classifyLetter(char) {
if (!/^[a-zA-Z]$/.test(char)) {
return "not a letter";
}
switch (char.toLowerCase()) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return "vowel";
default:
return "consonant";
}
}
// Bonus 1 Solution:
function romanToNumber(numeral) {
switch (numeral.toUpperCase()) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}
// Bonus 2 Solution:
function rpsls(player1, player2) {
if (player1 === player2) return "Tie";
const wins = {
scissors: ["paper", "lizard"],
paper: ["rock", "spock"],
rock: ["lizard", "scissors"],
lizard: ["spock", "paper"],
spock: ["scissors", "rock"]
};
if (wins[player1].includes(player2)) {
return "Player 1 wins";
}
return "Player 2 wins";
}
*/