WessCoby
8/7/2019 - 6:34 AM

format_order.js

//! Exercise of the day
/** 
 * Some new cashiers started to work at our restaurant.
 * All the orders they create look something like this:
 * 
 ** "milkshakepizzachickenfriescokeburgerpizzasandwitchmilkshakepizza"
 * 
 * Their preference is to get the orders as a nice clean string with spaces and capitals like so:
 * 
 ** "Burger Fries Chicken Pizza Pizza Pizza Sandwitch Milkshake MilkShake Coke" 
 * 
 *? Write a Program to make this happen.
*/

let order = "milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza";

const format_order = orderString => {
    // Predefined array of items on the menu
    const itemsOnMenu = ['Burger', 'Chicken', 'Coke', 'Fries', 'Milkshake', 'Pizza', 'Sandwich'];
    // Capitalize first letter of string
    const capitalize = word => word.replace(/^\w/, firstLetter => firstLetter.toUpperCase());
    
    let orderFormat = [];
    // For every item in the predefined array, check for matches in orderString add result to orderFormat
    itemsOnMenu.forEach(item => {
        let pattern = RegExp(item, 'ig');
        orderFormat.push(orderString.match(pattern).map(capitalize).join(" "));
    })

    return orderFormat.join(" ");
};

console.log(format_order(order));

//* Burger Chicken Coke Fries Milkshake Milkshake Pizza Pizza Pizza Sandwich