As per this Codewars challenge, I need to create some simple logic for keeping track of all of the words that appear in a string.
INSTRUCTIONS
Some new cashiers started to work at your restaurant.
They are good at taking orders, but they don't know how to capitalize words, or use a space bar!
All the orders they create look something like this:
"milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"
The kitchen staff are threatening to quit, because of how difficult it is to read the orders.
Their preference is to get the orders as a nice clean string with spaces and capitals like so:
"Burger Fries Chicken Pizza Pizza Pizza Sandwich Milkshake Milkshake Coke"
The kitchen staff expect the items to be in the same order as they appear in the menu.
The menu items are fairly simple, there is no overlap in the names of the items:
EDIT Following the .match()
logic, I've created an array of all items that appear in the input. But I don't know the quickest way to sort them according to their order of appearance in the original string:
function getOrder(order) {
let menu = ['Burger', 'Fries', 'Chicken', 'Pizza', 'Sandwich', 'Onionrings', 'Milkshake', 'Coke'];
let finalOrder = order.split(/(burger|fries|chicken|pizza|sandwich|onionrings|milkshake|coke)/i);
finalOrder = finalOrder.filter((element) => element !== null || element !== "");
finalOrder = finalOrder.map((element) => element.charAt(0).toUpperCase() + element.slice(1));
finalOrder = finalOrder.sort((a, b) => {
if (menu.indexOf(a) > menu.indexOf(b)) {
return 1;
}
else {
return -1;
}
});
return finalOrder.join(" ").trim(/\s/);
}
console.log(getOrder("milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"));
function getOrder(input) {
let menu = ['Burger','Fries','Chicken','Pizza','Sandwich','Onionrings','Milkshake','Coke'];
let items = input.match(/(burger|fries|chicken|pizza|sandwich|onionrings|milkshake|coke)/gi);
items = items.map((element) => element.charAt(0).toUpperCase() + element.slice(1));
items = items.sort((a, b) => {
if (menu.indexOf(a) > menu.indexOf(b)) {
return 1;
}
else {
return -1;
}
});
return items.join(" ");
}
console.log(getOrder("milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"));