From 6486f3409c233b0c0511042522dbb3519e94fa74 Mon Sep 17 00:00:00 2001 From: Swar1904 Date: Tue, 8 Jul 2025 19:12:23 -0500 Subject: [PATCH 1/2] finished --- arrays.js | 211 +++++++++++++++++++++------------------------------ callbacks.js | 162 +++++++++++++++++++++------------------ objects.js | 42 +++++++++- 3 files changed, 215 insertions(+), 200 deletions(-) diff --git a/arrays.js b/arrays.js index 37faed2..5aeeb05 100644 --- a/arrays.js +++ b/arrays.js @@ -1,141 +1,106 @@ -/* -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 +/* No need to redeclare 'inventory' if it already exists. + If you want a better word, you could use 'stock' or 'items' instead of 'inventory'. + For example: + const stock = ["Apples", "Bread", "Milk", "Eggs"]; + Then update the rest of the code to use 'stock' instead of '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); -/* -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")); // "Ali is present." +console.log(isPresent("Zainab")); // "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 โœ๏ธ - - - - - - - -/* -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!" - ---- - -### Input Data - +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); +printLeaderboard(); + + +// ๐ŸŒŸ 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(); \ No newline at end of file diff --git a/callbacks.js b/callbacks.js index 3fadb3f..8386ce4 100644 --- a/callbacks.js +++ b/callbacks.js @@ -1,75 +1,87 @@ -/* -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 โœ๏ธ +// app.js + +// 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 questions (Fisherโ€‘Yates) :contentReference[oaicite:6]{index=6} +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(user, correct, done) { + if (user.toLowerCase() === correct.toLowerCase()) { + console.log("โœ”๏ธ Correct!"); + done(true); + } else { + console.log(`โŒ Incorrect. The correct answer is ${correct}.`); + done(false); + } +} + +// Quiz setup +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; + +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(t => checkTemperature(t, temperatureCallback)); + +console.log("\n๐Ÿ“ Starting quiz (10s per question):"); +next() diff --git a/objects.js b/objects.js index e2426e9..ba27b63 100644 --- a/objects.js +++ b/objects.js @@ -22,7 +22,19 @@ const gamerProfile = { isOnline: false }; -updateOnlineStatus(gamerProfile, true); +function updateOnlineStatus(gamerProfile, status) { + gamerProfile.isOnline = status; + if (status) { + console.log(`${gamerProfile.username} is now online.`); + } else { + console.log(`${gamerProfile.username} is now offline.`); + } +} + +// Example usage: +updateOnlineStatus(gamerProfile, true); +// Output: "ShadowSlayer is now online." + Expected Output: "ShadowSlayer is now online." @@ -56,7 +68,18 @@ const dress = { inStock: true }; -checkAvailability(dress); +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.`); + } +} + +// Example usage: +checkAvailability(dress); +// Output: "Evening Gown is available in size M." + Expected Output: "Evening Gown is available in size M." @@ -94,6 +117,21 @@ const supercar = { } }; +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]}`); + } +} + +function capitalize(str) { + return str.charAt(0).toUpperCase() + str.slice(1); +} + +// Example usage: addFeature(supercar, "turbo"); Expected Output: From b6eb0de9697e60848c0efbff523587a7fb684715 Mon Sep 17 00:00:00 2001 From: Swar1904 Date: Tue, 8 Jul 2025 19:24:59 -0500 Subject: [PATCH 2/2] fished --- arrays.js | 41 +++++++++++++++++------- callbacks.js | 34 +++++++++++--------- objects.js | 88 ++++++---------------------------------------------- 3 files changed, 59 insertions(+), 104 deletions(-) diff --git a/arrays.js b/arrays.js index 5aeeb05..c91e8d0 100644 --- a/arrays.js +++ b/arrays.js @@ -1,11 +1,6 @@ -// โœ… Task 1: Grocery store Restock ๐Ÿ›’๐ŸŽ +// โœ… Task 1: Grocery Store Restock ๐Ÿ›’๐ŸŽ const inventory = ["Apples", "Bread", "Milk", "Eggs"]; -/* No need to redeclare 'inventory' if it already exists. - If you want a better word, you could use 'stock' or 'items' instead of 'inventory'. - For example: - const stock = ["Apples", "Bread", "Milk", "Eggs"]; - Then update the rest of the code to use 'stock' instead of 'inventory'. -*/ + // Add "Oranges" and "Bananas" inventory.push("Oranges", "Bananas"); @@ -14,6 +9,8 @@ inventory.shift(); // Print updated inventory console.log("Updated inventory:", inventory); +// Output: Updated inventory: [ 'Bread', 'Milk', 'Eggs', 'Oranges', 'Bananas' ] + // โœ… Task 2: Student Attendance Checker ๐Ÿ“šโœ… @@ -28,8 +25,9 @@ function isPresent(name) { } // Example usage: -console.log(isPresent("Ali")); // "Ali is present." -console.log(isPresent("Zainab")); // "Zainab is absent." +console.log(isPresent("Ali")); // Output: Ali is present. +console.log(isPresent("Zainab")); // Output: Zainab is absent. + // โœ… Task 3: Top Scorers Leaderboard ๐Ÿ†โšฝ @@ -57,8 +55,16 @@ function printLeaderboard() { } // Example: -updateScore("Ronaldo", 2); +updateScore("Ronaldo", 2); // Ronaldo now has 5 printLeaderboard(); +/* +Output: +Leaderboard: +Messi: 5 +Ronaldo: 5 +Neymar: 4 +*/ + // ๐ŸŒŸ Stretch Task: The Ultimate Treasure Hunt ๐Ÿ—บ๏ธ๐Ÿ’Ž๐Ÿดโ€โ˜ ๏ธ @@ -103,4 +109,17 @@ function treasureHunt() { } // Run the treasure hunt -treasureHunt(); \ No newline at end of file +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 8386ce4..04f0971 100644 --- a/callbacks.js +++ b/callbacks.js @@ -1,6 +1,4 @@ -// app.js - -// Task 1: Welcome ๐Ÿ“จ +// โœ… Task 1: Welcome ๐Ÿ“จ function sendMessage(name, cb) { cb(name); } @@ -8,7 +6,8 @@ function welcomeCallback(username) { console.log(`\n๐Ÿ“จ Welcome, ${username}!\n`); } -// Task 2: Temperature Checker ๐ŸŒก๏ธ + +// โœ… Task 2: Temperature Checker ๐ŸŒก๏ธ function checkTemperature(temp, cb) { cb(temp); } @@ -17,7 +16,8 @@ function temperatureCallback(temp) { console.log(`${temp}ยฐC is ${status}.`); } -// Task 3: Quiz with Randomization & Timer โฑ๏ธ + +// โœ… Task 3: Quiz with Randomization & Timer โฑ๏ธ const readline = require('readline'); const rl = readline.createInterface({ @@ -25,7 +25,7 @@ const rl = readline.createInterface({ output: process.stdout }); -// Shuffle questions (Fisherโ€‘Yates) :contentReference[oaicite:6]{index=6} +// Shuffle function (Fisherโ€‘Yates) function shuffle(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); @@ -45,26 +45,27 @@ function askQuestion(qObj, cb, timeLimit, done) { }); } -function answerCallback(user, correct, done) { - if (user.toLowerCase() === correct.toLowerCase()) { +function answerCallback(userAnswer, correctAnswer, done) { + if (userAnswer.toLowerCase() === correctAnswer.toLowerCase()) { console.log("โœ”๏ธ Correct!"); done(true); } else { - console.log(`โŒ Incorrect. The correct answer is ${correct}.`); + console.log(`โŒ Incorrect. The correct answer is ${correctAnswer}.`); done(false); } } -// Quiz setup +// 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; +const TIME_LIMIT = 10; // seconds function next() { if (idx >= quiz.length) { @@ -72,6 +73,7 @@ function next() { rl.close(); return; } + askQuestion(quiz[idx], answerCallback, TIME_LIMIT, isCorrect => { if (isCorrect) score++; idx++; @@ -79,9 +81,13 @@ function next() { }); } -// Run all tasks +// โœ… Run all tasks sendMessage("Amina", welcomeCallback); -[35, 22, 10].forEach(t => checkTemperature(t, temperatureCallback)); + +[35, 22, 10].forEach(temp => { + checkTemperature(temp, temperatureCallback); +}); console.log("\n๐Ÿ“ Starting quiz (10s per question):"); -next() +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 ba27b63..099281e 100644 --- a/objects.js +++ b/objects.js @@ -1,21 +1,4 @@ -/* -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, @@ -31,37 +14,12 @@ function updateOnlineStatus(gamerProfile, status) { } } -// Example usage: updateOnlineStatus(gamerProfile, true); // Output: "ShadowSlayer is now online." -Expected Output: -"ShadowSlayer is now online." -*/ - -// โœ๏ธ Solve it here โœ๏ธ - - -/* -Task 2: Dress Inventory Checker ๐Ÿ‘— ๐Ÿ‘— ๐Ÿ‘— ๐Ÿ‘— ๐Ÿ‘— - -You are helping a fashion designer manage their dress inventory. - -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", @@ -76,39 +34,12 @@ function checkAvailability(dress) { } } -// Example usage: checkAvailability(dress); // Output: "Evening Gown is available in size M." -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. - -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. -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, @@ -117,6 +48,10 @@ 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}.`); @@ -127,18 +62,13 @@ function addFeature(supercar, featureName) { } } -function capitalize(str) { - return str.charAt(0).toUpperCase() + str.slice(1); -} - -// Example usage: 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."