diff --git a/arrays.js b/arrays.js index 37faed2..c91e8d0 100644 --- a/arrays.js +++ b/arrays.js @@ -1,141 +1,125 @@ -/* -Task 1: Grocery Store Restock ๐Ÿ›’๐ŸŽ - -You manage a grocery store. The array `inventory` shows the items currently in stock. - -1. Add "Oranges" and "Bananas" to the inventory. -2. Remove the first item from the array. -3. Print the updated inventory. - -Array: +// โœ… Task 1: Grocery Store Restock ๐Ÿ›’๐ŸŽ const inventory = ["Apples", "Bread", "Milk", "Eggs"]; -Expected Output: -- Updated inventory -*/ +// Add "Oranges" and "Bananas" +inventory.push("Oranges", "Bananas"); -// โœ๏ธ Solve it here โœ๏ธ +// Remove the first item +inventory.shift(); +// Print updated inventory +console.log("Updated inventory:", inventory); +// Output: Updated inventory: [ 'Bread', 'Milk', 'Eggs', 'Oranges', 'Bananas' ] - -/* -Task 2: Student Attendance Checker ๐Ÿ“šโœ… - -You are a teacher tracking attendance. Use the `students` array to check if specific students are present. - -1. Write a function called `isPresent` that takes a student's name as input. -2. Use an if statement to check if the name exists in the `students` array. - - If present, return "[name] is present." - - If not present, return "[name] is absent." - -Array: +// โœ… Task 2: Student Attendance Checker ๐Ÿ“šโœ… const students = ["Ali", "Fatima", "Hassan", "Layla"]; -Example: -Input: isPresent("Ali") -Output: "Ali is present." -*/ - -// โœ๏ธ Write your function here โœ๏ธ - +function isPresent(name) { + if (students.includes(name)) { + return `${name} is present.`; + } else { + return `${name} is absent.`; + } +} +// Example usage: +console.log(isPresent("Ali")); // Output: Ali is present. +console.log(isPresent("Zainab")); // Output: Zainab is absent. - -/* -Task 3: Top Scorers Leaderboard ๐Ÿ†โšฝ - -You are creating a leaderboard for a soccer game. The array `topScorers` contains the names of players and their scores. - -1. Write a function called `updateScore` that takes a player's name and a score to add. If the player exists in the leaderboard, add the score to their total. If not, add the player to the array with the given score. -2. Write another function called `printLeaderboard` that sorts the leaderboard in descending order of scores and prints it. - -Array: +// โœ… Task 3: Top Scorers Leaderboard ๐Ÿ†โšฝ const topScorers = [ { name: "Messi", score: 5 }, { name: "Ronaldo", score: 3 }, { name: "Neymar", score: 4 } ]; -Example: -Input: updateScore("Ronaldo", 2) -Output: Sorted leaderboard with updated scores -*/ - -// โœ๏ธ Write your functions here โœ๏ธ - - - - - - - +function updateScore(playerName, scoreToAdd) { + const player = topScorers.find(p => p.name === playerName); + if (player) { + player.score += scoreToAdd; + } else { + topScorers.push({ name: playerName, score: scoreToAdd }); + } +} + +function printLeaderboard() { + const sorted = [...topScorers].sort((a, b) => b.score - a.score); + console.log("Leaderboard:"); + sorted.forEach(player => { + console.log(`${player.name}: ${player.score}`); + }); +} + +// Example: +updateScore("Ronaldo", 2); // Ronaldo now has 5 +printLeaderboard(); /* -STRETCH TASK: **The Ultimate Treasure Hunt** ๐Ÿ—บ๏ธ๐Ÿ’Ž๐Ÿดโ€โ˜ ๏ธ - -You are a legendary adventurer searching for the ultimate treasure! -The treasure is hidden in a remote island, and you have a map with a series -of clues stored in arrays. Your task is to navigate through the clues, -decode them, and uncover the treasure. - -Hereโ€™s the plan: - -1. **Clue Checkpoint**: - - Write a function called `findClue` that takes a `clues` array and a clue name (string). - - Check if the clue exists in the array: - - If it exists, return "Clue [name] found!" - - If it doesnโ€™t exist, return "Clue [name] is missing, search again!" - -2. **Decipher Hidden Messages**: - - Each clue is a scrambled message stored in the `clueMessages` array. - - Write a function called `decipherMessage` that uses a loop to reverse each message in the `clueMessages` array and return the updated array. - -3. **Follow the Treasure Map**: - - You are given an array of steps to reach the treasure: `treasureMapSteps`. - - Write a function called `followSteps` that: - - Uses a loop to log each step in the journey. - - Tracks your current position in the array. - - Stops if the step says "Danger" and logs: "Stopped at danger. Cannot continue." - -4. **Final Treasure Hunt**: - - Use all the above functions to: - - Check if all the clues exist. - - Decipher the messages. - - Follow the map. - - If all clues are found, all steps are completed without danger, and the final step is "Treasure," log: - "Congratulations! You found the ultimate treasure!" - - Otherwise, log: "The treasure remains hidden. Try again!" +Output: +Leaderboard: +Messi: 5 +Ronaldo: 5 +Neymar: 4 +*/ ---- -### Input Data +// ๐ŸŒŸ Stretch Task: The Ultimate Treasure Hunt ๐Ÿ—บ๏ธ๐Ÿ’Ž๐Ÿดโ€โ˜ ๏ธ const clues = ["Map", "Compass", "Key", "Shovel"]; -const clueMessages = ["ppaM", "ssapmoC", "yeK", "levohS"]; // scrambled clues -const treasureMapSteps = ["Start at the beach", "Cross the forest", "Climb the mountain", "Danger", "Treasure"]; - ---- - -### Example Usage - -findClue(clues, "Map"); -// Output: "Clue Map found!" - -decipherMessage(clueMessages); -// Output: ["Map", "Compass", "Key", "Shovel"] - -followSteps(treasureMapSteps); -// Output: -// "Step 1: Start at the beach" -// "Step 2: Cross the forest" -// "Step 3: Climb the mountain" -// "Stopped at danger. Cannot continue." - -Final Output: -- "The treasure remains hidden. Try again!" (if danger is encountered) -- "Congratulations! You found the ultimate treasure!" (if all conditions are met) +const clueMessages = ["ppaM", "ssapmoC", "yeK", "levohS"]; +const treasureMapSteps = ["Start at the beach", "Cross the forest", "Climb the mountain", "Find the cave", "Treasure"]; + +function findClue(clueArray, clueName) { + return clueArray.includes(clueName) + ? `Clue ${clueName} found!` + : `Clue ${clueName} is missing, search again!`; +} + +function decipherMessage(messages) { + return messages.map(msg => msg.split("").reverse().join("")); +} + +function followSteps(steps) { + for (let i = 0; i < steps.length; i++) { + const step = steps[i]; + console.log(`Step ${i + 1}: ${step}`); + if (step === "Danger") { + console.log("Stopped at danger. Cannot continue."); + return false; + } + } + return steps[steps.length - 1] === "Treasure"; +} + +function treasureHunt() { + const decoded = decipherMessage(clueMessages); + console.log("Decoded Messages:", decoded); + + const allCluesFound = clues.every(clue => decoded.includes(clue)); + const completed = followSteps(treasureMapSteps); + + if (allCluesFound && completed) { + console.log("๐ŸŽ‰ Congratulations! You found the ultimate treasure!"); + } else { + console.log("๐Ÿ’” The treasure remains hidden. Try again!"); + } +} + +// Run the treasure hunt +treasureHunt(); +/* +Expected Output: +Decoded Messages: [ 'Map', 'Compass', 'Key', 'Shovel' ] +Step 1: Start at the beach +Step 2: Cross the forest +Step 3: Climb the mountain +Step 4: Find the cave +Step 5: Treasure +๐ŸŽ‰ Congratulations! You found the ultimate treasure! */ +// } +// \ No newline at end of file diff --git a/callbacks.js b/callbacks.js index 3fadb3f..04f0971 100644 --- a/callbacks.js +++ b/callbacks.js @@ -1,75 +1,93 @@ -/* -Task 1: Simple Welcome Message ๐Ÿ’Œ๐Ÿ’Œ๐Ÿ’Œ๐Ÿ’Œ - -You are building a simple messaging system. Write a function called `sendMessage` that: -1. Takes a user name and a callback function as arguments. -2. The callback function should log a welcome message. - -Steps: -- Create the callback function to log: "Welcome, [name]!" - -Example: -Input: -sendMessage("Amina", theCallBackFunction); - -Expected Output: -- "Welcome, Amina!" -*/ - -// โœ๏ธ Solve it here โœ๏ธ - - - - -/* -Task 2: Temperature Checker ๐ŸŒก๏ธ๐ŸŒก๏ธ๐ŸŒก๏ธ๐ŸŒก๏ธ - - -You are creating a temperature monitoring system. Write a function called `checkTemperature` that: -1. Takes a temperature value and a callback function as arguments. -2. The callback function should evaluate whether the temperature is "Hot", "Warm", or "Cold" based on the following: - - "Hot" if the temperature is above 30. - - "Warm" if the temperature is between 15ยฐC and 30. - - "Cold" if the temperature is below 15. - -Steps: -- Create the callback function to evaluate and log: - - "[temperature]ยฐC is Hot/Warm/Cold." - -Example: -Input: -checkTemperature(35, theCallBackFunction); - -Expected Output: -- "35ยฐC is Hot." -- "22ยฐC is Warm." -- "10ยฐC is Cold." -*/ - -// โœ๏ธ Solve it here โœ๏ธ - - - - -/* -STRETCH: Task 3: Quiz Evaluator ๐Ÿ“š๐Ÿ“š๐Ÿ“š๐Ÿ“š - -You are building a quiz system. Write a function called `evaluateAnswer` that: -1. Takes a question, a correct answer, and a callback function as arguments. -2. The callback function should compare the user's answer with the correct answer and log whether the answer is correct or not. - -Steps: -- Create the callback function to evaluate: - - If the user's answer matches the correct answer, log: "Correct!" - - Otherwise, log: "Incorrect. The correct answer is [correctAnswer]." - -Example: -Input: -evaluateAnswer("What is 5 + 5?", "10", TheCallBackFunction); - -Expected Output: -- If user's input is "10": "Correct!" -- If user's input is "15": "Incorrect. The correct answer is 10." -*/ - -// โœ๏ธ Solve it here โœ๏ธ +// โœ… Task 1: Welcome ๐Ÿ“จ +function sendMessage(name, cb) { + cb(name); +} +function welcomeCallback(username) { + console.log(`\n๐Ÿ“จ Welcome, ${username}!\n`); +} + + +// โœ… Task 2: Temperature Checker ๐ŸŒก๏ธ +function checkTemperature(temp, cb) { + cb(temp); +} +function temperatureCallback(temp) { + const status = temp > 30 ? "Hot" : temp >= 15 ? "Warm" : "Cold"; + console.log(`${temp}ยฐC is ${status}.`); +} + + +// โœ… Task 3: Quiz with Randomization & Timer โฑ๏ธ +const readline = require('readline'); + +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout +}); + +// Shuffle function (Fisherโ€‘Yates) +function shuffle(array) { + for (let i = array.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [array[i], array[j]] = [array[j], array[i]]; + } +} + +function askQuestion(qObj, cb, timeLimit, done) { + let timeout = setTimeout(() => { + console.log(`\nโฐ Time's up! The correct answer is: ${qObj.answer}`); + done(false); + }, timeLimit * 1000); + + rl.question(`${qObj.question} `, answer => { + clearTimeout(timeout); + cb(answer.trim(), qObj.answer, done); + }); +} + +function answerCallback(userAnswer, correctAnswer, done) { + if (userAnswer.toLowerCase() === correctAnswer.toLowerCase()) { + console.log("โœ”๏ธ Correct!"); + done(true); + } else { + console.log(`โŒ Incorrect. The correct answer is ${correctAnswer}.`); + done(false); + } +} + +// Quiz questions +const quiz = [ + { question: "What is 5 + 5?", answer: "10" }, + { question: "Capital of France?", answer: "Paris" }, + { question: "Color from blue + yellow?", answer: "Green" } +]; + +shuffle(quiz); + +let score = 0, idx = 0; +const TIME_LIMIT = 10; // seconds + +function next() { + if (idx >= quiz.length) { + console.log(`\n๐ŸŽ‰ Quiz complete! Your score: ${score}/${quiz.length}`); + rl.close(); + return; + } + + askQuestion(quiz[idx], answerCallback, TIME_LIMIT, isCorrect => { + if (isCorrect) score++; + idx++; + next(); + }); +} + +// โœ… Run all tasks +sendMessage("Amina", welcomeCallback); + +[35, 22, 10].forEach(temp => { + checkTemperature(temp, temperatureCallback); +}); + +console.log("\n๐Ÿ“ Starting quiz (10s per question):"); +next(); +// The quiz will run in the console, and you can answer the questions interactively. \ No newline at end of file diff --git a/objects.js b/objects.js index e2426e9..099281e 100644 --- a/objects.js +++ b/objects.js @@ -1,91 +1,45 @@ -/* -Task 1: Gamer Profile Manager ๐ŸŽฎ ๐ŸŽฎ ๐ŸŽฎ ๐ŸŽฎ - -You are creating a system to manage a gamer's profile. - -Steps: -1. Create an object named `gamerProfile` with the following properties: - - `username` (string): The gamer's username. - - `level` (number): The gamer's level. - - `isOnline` (boolean): Whether the gamer is currently online. - -2. Write a function `updateOnlineStatus` that: - - Takes the `gamerProfile` object and a boolean `status` as arguments. - - Updates the `isOnline` property based on the `status`. - - Logs: "[username] is now online." or "[username] is now offline." - -Example: -Input: +// โœ… Task 1: Gamer Profile Manager ๐ŸŽฎ ๐ŸŽฎ ๐ŸŽฎ ๐ŸŽฎ const gamerProfile = { username: "ShadowSlayer", level: 5, isOnline: false }; -updateOnlineStatus(gamerProfile, true); - -Expected Output: -"ShadowSlayer is now online." -*/ - -// โœ๏ธ Solve it here โœ๏ธ - - - -/* -Task 2: Dress Inventory Checker ๐Ÿ‘— ๐Ÿ‘— ๐Ÿ‘— ๐Ÿ‘— ๐Ÿ‘— +function updateOnlineStatus(gamerProfile, status) { + gamerProfile.isOnline = status; + if (status) { + console.log(`${gamerProfile.username} is now online.`); + } else { + console.log(`${gamerProfile.username} is now offline.`); + } +} -You are helping a fashion designer manage their dress inventory. +updateOnlineStatus(gamerProfile, true); +// Output: "ShadowSlayer is now online." -Steps: -1. Create an object named `dress` with the following properties: - - `name` (string): Name of the dress. - - `size` (string): Size of the dress. - - `inStock` (boolean): Whether the dress is available. -2. Write a function `checkAvailability` that: - - Takes the `dress` object as an argument. - - Logs: "[name] is available in size [size]." if the dress is in stock. - - Logs: "[name] is out of stock." if the dress is not available. -Example: -Input: +// โœ… Task 2: Dress Inventory Checker ๐Ÿ‘— ๐Ÿ‘— ๐Ÿ‘— ๐Ÿ‘— ๐Ÿ‘— const dress = { name: "Evening Gown", size: "M", inStock: true }; -checkAvailability(dress); - -Expected Output: -"Evening Gown is available in size M." -*/ - -// โœ๏ธ Solve it here โœ๏ธ - - - -/* -Task 3: Supercar Feature Adder ๐Ÿš— ๐Ÿš— ๐Ÿš— ๐Ÿš— - -You are building a configurator for a supercar. +function checkAvailability(dress) { + if (dress.inStock) { + console.log(`${dress.name} is available in size ${dress.size}.`); + } else { + console.log(`${dress.name} is out of stock.`); + } +} -Steps: -1. Create an object named `supercar` with the following properties: - - `model` (string): The car's model. - - `price` (number): The base price. - - `features` (object): An object with a `color` property. +checkAvailability(dress); +// Output: "Evening Gown is available in size M." -2. Write a function `addFeature` that: - - Takes the `supercar` object and a feature name (string) as arguments. - - Adds the feature to the `features` object and sets it to `true`. - - Logs: "[featureName] has been added to [model]." -3. Use a **for...in loop** to log all the features of the `supercar` object. -Example: -Input: +// โœ… Task 3: Supercar Feature Adder ๐Ÿš— ๐Ÿš— ๐Ÿš— ๐Ÿš— const supercar = { model: "Ferrari SF90", price: 500000, @@ -94,13 +48,27 @@ const supercar = { } }; +function capitalize(str) { + return str.charAt(0).toUpperCase() + str.slice(1); +} + +function addFeature(supercar, featureName) { + supercar.features[featureName] = true; + console.log(`${capitalize(featureName)} has been added to ${supercar.model}.`); + + console.log("Features:"); + for (const feature in supercar.features) { + console.log(`- ${feature}: ${supercar.features[feature]}`); + } +} + addFeature(supercar, "turbo"); +/* Expected Output: "Turbo has been added to Ferrari SF90." Features: - color: Red - turbo: true */ - -// โœ๏ธ Solve it here โœ๏ธ +// Output: "Turbo has been added to Ferrari SF90."