Build a Lunch Picker Program - Build a Lunch Picker Program

My code works, but I’d appreciate your opinion on whether it’s written well or if it’s more complex than necessary. Specifically the “showLunchMenu” section. If so, how can I simplify it? Thanks!

const lunches = [];

function addLunchToEnd(arr, str) {

arr.push(str);

console.log(`${str} added to the end of the lunch menu.`);

return arr;

}


function addLunchToStart(arr, str) {

arr.unshift(str);

console.log(`${str} added to the start of the lunch menu.`);

return arr;

}


function removeLastLunch(arr) {

if (arr.length > 0) {

let itemRemoved = arr.pop();

console.log(`${itemRemoved} removed from the end of the lunch menu.`);

return arr;

} else {

console.log(“No lunches to remove.”);

return arr;

}

}


function removeFirstLunch(arr) {

let itemRemoved = arr.shift();

if (arr.length > 0) {

console.log(`${itemRemoved} removed from the start of the lunch menu.`);

return arr;

} else {

console.log(“No lunches to remove.”);

return arr;

}

}


function getRandomLunch(arr) {

let min = 0;

let max = arr.length;

let randomArrayIndex = Math.floor(Math.random() * (max - min) + min);

if(max > 0 && randomArrayIndex < max) {

console.log(`Randomly selected lunch: ${arr[randomArrayIndex]}`);

} else {

console.log(“No lunches available.”);

}

}


function showLunchMenu(arr) {

if (arr.length > 0) {

let i = 0;

let str1 = "Menu items: "

let str2 = “”;

if (arr.length > 1) {

for(i; i < arr.length; ++i) {

if(i < arr.length-1) {

str2 += arr[i] + ", ";

      } else {

str2 += arr[i];

      }

    } console.log(str1 + str2)

  } else {

str2 +=  arr[i];

console.log(str1 + str2);

  } 

} else {

console.log(“The menu is empty.”);

}

}
1 Like

Hi @consistencyiskey, your solution works, but manual string concatenation inside the loop adds a bit of unnecessary complexity and can be less efficient for larger arrays….You could work with the built-in .join() method that JS already provides to handle building strings from an array, something like this:

code removed by moderator

hi @maryojo

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge. How to Help Someone with Their Code Using the Socratic Method

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

1 Like