Search code examples
javascriptarraysfor-loopiterationjavascript-objects

Vending Machine function in Javascript


I'm very new to Javascript: I've been working with it for a few weeks casually now. This is my first post, so I apologize if I'm not thorough enough, but I think I have been below!

I want to create a function VendingMachine(snack, cash) that has a list of 4 items and their prices that takes 2 arguments, "snack name" (snack) and "cash inserted" (cash). I've tried making the list an object and an array and only have semi-success with the array, but I believe the object is truly the path I want to take because...

When using an array with nested arrays for the snacks list, the only problem is that if the for() loop doesn't find the "snack" value in any of the arrays, it prints 'undefined' instead of "Sorry, try again."

With the list of items in the machine in an object, I want to check that "snack ==== object.KEY" and that "cash >= VALUE" of that KEY. My problem here is that I don't know the syntax concerning objects well, and the explanations and answers I see other people posting are too abstract for me to comprehend at the moment, or are more complex loops/problems and don't really seem to be applicable to my situation. All things except this (which I couldn't figure out either/didn't work):

 for(var key in objects) {
    var value = objects[key];
}

// Using an array

    function vendingMachine(snack, cash) {
    //declare nested arrays of snacks & costs
    var snacks = [
        ["Espresso", 1],
        ["Cappuccino", 2.50],
        ["Chocolate bar", 2],
        ["Potato Chips", 3.50]
    ]
    //iterate through array to match snack and check funds
    for (var i = 0; i < snacks.length; i++) {
        if (snack === snacks[i][0] && cash >= snacks[i][1]) {
            if (snack === "Potato Chips") {
                console.log("Your " + snack + " have been served");
            } else {
                console.log("Your " + snack + " has been served");
            }
        }
        else if (snack === snacks[i][0] && cash <= snacks[i][1]) {
            console.log("Insufficient funds. Please insert more cash.");
        }
    }
}


// Using an object (incomplete or perhaps just VERY incorrect, I'm aware, hence why I'm here to understand why!)

    function vendingMachine(snack, cash) {
    //declare nested arrays of snacks & costs
    var snacks = {
        "Espresso": 1,
        "Cappuccino": 2.50,
        "Chocolate bar": 2,
        "Potato Chips": 3.50
    }

    if (snack === snacks.hasOwnProperty() && cash >= snacks.key) {
        if (snack === "Potato Chips") {
            console.log("Your " + snack + " have been served");
        } else {
            console.log("Your " + snack + " has been served");
        }
    }
    else if (snack === snacks.hasOwnProperty() && cash <= snacks.key) {
        console.log("Insufficient funds. Please insert more cash.");
    }
    else if (snack != snacks.hasOwnProperty()) {
        console.log(snack + " does not exist. Please try again.") //returns undefined
    }
}

Solution

  • Using some modern javascript I have updated your vending machine and also made it return change.

    function vendingMachine(snack, cash) {
        const snacks = [
            { name: 'Espresso', price: 1 },
            { name: 'Cappuccino', price: 2.50 },
            { name: 'Chocolate', price: 2 },
            { name: 'Potato', price: 3.50 }
        ];
    
        const selected_snack = snacks.find(item => item.name === snack);
    
        if (selected_snack) {
            if (selected_snack.price === cash) {
                return `Your ${snack} have been served`;
            }
            else {
                if (selected_snack.price > cash) {
                    return `Insufficient funds. Please insert more cash.`;
                }
                else {
                    return `Your ${snack} have been served. Here is your $${cash - selected_snack.price} change.`;
                }
            }
        }
    
        else {
            return `${snack} does not exist. Please try again`
        }
    };
    
    console.log(vendingMachine('Espresso', 12));
    

    First of we convert the snacks into an array of objects, each one of them having a name and a price keys.

    Next we use the Array.find() method to search the list of snacks for the snack in question by it's name. The function will return a single object, if you want multiple results that match some criterion use Array.filter() instead.

    So if we have a match we can say if (selected_snack) which evaluates to true, otherwise if there is not match then selected_snack would be undefined so basically a less verbose way to say if (selected_snack !== undefined).

    The rest of the function is almost self-explanatory, the only changes I made is that I'm not console logging inside of the function, instead I am using a return statement.

    Also in case you wonder what those weird looking ${} things are, check out about Template Literals, extremely easy and convenient to use so you don't have to write ugly code such as "Your " + snack + " have been served".

    I hope that helps, if you have any questions let me know.