JavaScript's Automated Retail Machine Feature

I'm still in the early stages of learning Javascript, having dabbled with it for a couple of weeks. This marks my first time posting, so I apologize if my explanation is not comprehensive enough, but I'll do my best!

My goal is to create a function called VendingMachine(snack, cash) that contains a list of 4 items along with their respective prices, taking two arguments: "snack name" (snack) and the amount of "cash inserted" (cash). I've experimented with both objects and arrays to store the list, finding some success with arrays, but I believe objects are the way to go because...

When using an array with nested arrays for the snack list, the issue arises when the 'for()' loop fails to find the matching value for "snack", resulting in 'undefined' output instead of displaying "Sorry, try again."

By storing the item list in the machine as an object, my aim is to verify that "snack === object.KEY" and that "cash >= VALUE" corresponding to that KEY. However, my struggle lies in lacking familiarity with object syntax, making it challenging for me to grasp explanations provided by others or apply them to my specific situation. The only thing that didn't work out was:

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

// Utilizing an array

    function vendingMachine(snack, cash) {
    //declaring nested arrays for snacks & costs
    var snacks = [
        ["Espresso", 1],
        ["Cappuccino", 2.50],
        ["Chocolate bar", 2],
        ["Potato Chips", 3.50]
    ]
    //looping through the 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.");
        }
    }
}


// Utilizing an object (still a work-in-progress or possibly extremely incorrect, seeking clarification!)

    function vendingMachine(snack, cash) {
    //declaring nested arrays for 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
    }
}

Answer №1

Incorporating some cutting-edge JavaScript techniques, I have revamped your vending machine to not only dispense snacks but also provide 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} has been served`;
        }
        else {
            if (selected_snack.price > cash) {
                return `Insufficient funds. Please insert more cash.`;
            }
            else {
                return `Your ${snack} has been served. Here is your $${cash - selected_snack.price} change.`;
            }
        }
    }

    else {
        return `${snack} does not exist. Please try again`
    }
};

console.log(vendingMachine('Espresso', 12));

To begin with, we transform the snacks into an array of objects, each containing a name and a price.

Subsequently, we utilize the Array.find() method to scan through the list of snacks for the specified snack based on its name. This function will return a singular object matching the criteria; for multiple matches, consider using Array.filter() instead.

If there is a match, the condition

if (selected_snack)</code is met, signifying true. Conversely, failing to find a match would result in <code>selected_snack
being undefined, essentially equivalent to
if (selected_snack !== undefined)
.

The remainder of the code is almost self-explanatory. The main modification lies in avoiding console logs within the function but opting for return statements instead.

For those curious about the ${} syntax, refer to information on Template Literals. These are incredibly easy and convenient to use, eliminating the need for cumbersome concatenation like

"Your " + snack + " has been served"
.

I trust this explanation clarifies matters. Feel free to reach out should you have any queries.

Answer №2

If I were to approach this problem, I would structure the list as an array of objects for better flexibility in adding additional snack details. Here's how I would organize the list:

const snacksList = [
  {
    "name": "Popcorn",
    "price": 99
  },
  {
    "name": "Candy",
    "price": 199
  }
];

With this setup, the vendingMachine function can be simplified to efficiently find the matching snack and price. It could look something like this:

function vendingMachine(itemName, itemPrice) {
  const selectedSnack = snacksList.find(snack => snack.name === itemName && itemPrice >= snack.price);

  if (selectedSnack) {
    console.log("Enjoy your " + itemName + "!");
  } else {
    console.log("Sorry, that snack is unavailable or you have insufficient funds.");
  }
}

I hope this solution proves to be helpful.

Answer №3

Identifying the issue with your code may be a bit challenging at first glance; one potential problem could be the way you are utilizing snacks.hasOwnProperty().

Object.hasOwnProperty requires an argument that is a key, and it will return a boolean value. Therefore, in this case, you should probably revise the code to something like snacks.hasOwnProperty(snack), which checks if the snacks object possesses the property snack.

The method of data storage is flexible, and you are close to achieving functionality. It's important to note that snacks.key attempts to retrieve the key property of snacks, which may not align with your intentions here. Instead, utilizing something akin to snacks[snack] would likely be more suitable. Both dot notation and square bracket notation can be used to access object properties.


Having outlined those points, provided below is some code exemplifying various new concepts in a straightforward manner, avoiding excessive abstraction. Do not worry excessively about arrow functions; they are essentially similar to regular functions but feature distinct syntax.

The following setup enables the creation of a generic function getSnack, which dynamically determines the appropriate means to retrieve snack data. This simplifies concerns regarding how the snack data is stored when using the function.

Subsequently, the code closely resembles your initial version; another aspect introduced here is array destructuring, offering a concise syntax option.

This information aims to provide guidance; feel free to inquire about any uncertainties.

const snacks = {
  "Espresso": 1,
  "Cappuccino": 2.50,
  "Chocolate bar": 2,
  "Potato Chips": 3.50
};

const snacksArray = [
  ["Espresso", 1],
  ["Cappuccino", 2.50],
  ["Chocolate bar", 2],
  ["Potato Chips", 3.50]
];

const getSnackFromArray = (array, itemName) => array
  .find(x => x[0] === itemName)

const getSnackFromObject = (snackDataObject, itemName) => (
  snackDataObject.hasOwnProperty(itemName)
    ? [itemName, snackDataObject[itemName]]
    : undefined
)

const getSnack = (data, itemName) => Array.isArray(data)
  ? getSnackFromArray(data, itemName)
  : getSnackFromObject(data, itemName)
  
const vendingMachine = (snack, cash) => {
  const snackData = getSnackFromObject(snacks, snack);
  
  if (snackData === undefined) {
    console.log(snack + " does not exist. Please try again.")
    return;
  }
  
  const [snackName, cost] = snackData;
  
  if (cash >= cost) {
    console.log("Your " + snack + " have been served")
  } else {
    console.log("Insufficient funds. Please insert more cash.")
  }
}

vendingMachine('Espresso', 1.1)
vendingMachine('Espresso', 1)
vendingMachine('Espresso', 0.9)
vendingMachine('Expresso', 0.9)

Answer №4

 function snackVending(snackType, money) {
// Create arrays of available snacks and their prices
var snacks = {
    "Pretzels": 1.50,
    "Soda": 2,
    "Popcorn": 3,
    "Candy bar": 1.25
}

if (snacks.hasOwnProperty(snackType) && money >= snacks[snackType]) {
    if (snackType === "Popcorn") {
        console.log("Enjoy your " + snackType);
    } else {
        console.log("Here is your " + snackType);
    }
}
else if (snacks.hasOwnProperty(snackType) && money < snacks[snackType]) {
    console.log("Not enough money. Please insert more cash.");
}
else if (!snacks.hasOwnProperty(snackType)) {
    console.log(snackType + " is not available. Please make another selection.") 
}

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Develop a revolutionary web tool integrating Node.js, MongoDb, and D3.js for unparalleled efficiency and functionality

I am exploring the creation of a web application that will showcase data gathered from various websites. To achieve this, my plan involves automating the process of data collection through web scraping. After collecting the data from these sites, I will fo ...

Converting strings into time formats in MongoDB

My string appears as follows: schedule_time = { start_time : "13:00", end_time : "14:10" } Now I need to convert it into time in MongoDB. I attempted using dateFromString but encountered some issues. The aggregation query: db.getCollection('appoi ...

Utilizing JSON.stringify with variables and arrays

Here's the code snippet I'm working with: var dictionary = "["; for (var i = 0; i < aElem.length; i++) { dictionary += "{Key:" + aElem[i].value + ",Value:" + bElem[i].value + "}" if (i < aElem.length - 1) di ...

Objects that are included into an array will end up with an undefined value

Currently, I am in the process of coding a command for my Discord bot that involves adding items to an array of objects stored within a JSON file. To achieve this functionality, I have implemented the following code snippet: let rawdata = fs.readFileSync(& ...

Ways to align div elements

I am currently in the process of developing my own custom animation player. Utilizing Three.js for object rendering has been successful so far. However, the challenge lies in incorporating control options at the bottom of the player interface (such as play ...

Failed request using Ajax

I've been trying to call a C# function using ajax, but for some reason it's not working. Here is the ajax call I'm making: $('#button1 button').click(function () { var username = "username_declared"; var firstname = "firs ...

What is the best way to send data from a header component to a separate container component?

Utilizing React-router-dom, I am able to seamlessly switch between components in the following setup: <Router> <div> <Header /> <NavigationBar /> <Switch> <Route exact path ...

Error message: Electron is unable to read properties of undefined, specifically the property 'receive'. Furthermore, the IPC is unable to receive arguments that were sent through an HTML iframe

I am currently working on passing light mode and language data from ipcMain to ipcRenderer via my preload script: Preload.js: const { contextBridge, ipcRenderer } = require("electron"); const ipc = { render: { send: ["mainMenuUpdate& ...

using pointers as parameters to retrieve the length of a string

I have been experimenting with pointers based on the concepts from the K&R book. I developed a program that successfully swaps integers but encountered an issue with a function that calculates the length of a string using pointers. After compiling an ...

Enhancing material appearance by incorporating color gradient through the extension of three.js Material class using the onBeforeCompile method

In my three.js scene, I have successfully loaded an .obj file using THREE.OBJLoader. Now, I am looking to add a linear color gradient along the z-axis to this object while keeping the MeshStandardMaterial shaders intact. Below is an example of a 2-color l ...

Implementing coordinate formatting in JavaScript [Node.js]

I'm looking to tweak the JSON output into this specific format: [ 50.87758, 5.78092 ], [ 52.87758, 5.48091 ] and so on. Currently, the output looks like this: [ { lat: 53.1799, lon: 6.98565 }, { lat: 52.02554, lon: 5.82181 }, { lat: 51.87335, l ...

Stripping HTML elements from the body of an HTML document using AJAX before transmitting it as data to the controller

My JSP page contains two buttons labeled "download" and "sendemail". When the "Sendmail" button is clicked, an ajax method is triggered to generate a PDF version of the HTML body and send it to the back-end controller. I attempted to utilize the following ...

Tips for displaying a loading message during an AJAX request?

My AJAX function is set up like this: function update_session(val) { var session_id_to_change=document.getElementById('select_path').value; $.ajax({ type: "GET", url: "/modify_path/", asy ...

Error: JSON parsing error encountered due to an unexpected token 'U' while trying to read a file with

Currently, I am utilizing Node.js version 12.14.1 and encountering a problem while attempting to parse a JSON file that includes the \U0001f970 character. The file's content that needs to be read and parsed is as follows: {"randomKey": ...

CUDA/C++ implementation for searching in a table of positive integers

Currently, I am working on optimizing a section of code for a CUDA application that involves mapping unsigned integer ranges to array indexes, like [0..~1000]: if n >= 0 and n < 8 then index 0 if n >= 8 and n < 10 then index 1 and so on. Cons ...

Having trouble with sluggish performance on openbim-components? The OrthoPerspectiveCamera tends to slow down or get stuck when zooming

While using the OrthoPerspectiveCamera in my App (from openbim-components package), I am facing an issue. Whenever I zoom into my model, it automatically switches to FirstPerson mode. This change makes it extremely slow to navigate and zoom in/out of the s ...

Is there a way to initiate an AJAX post request with the Authorization header for the initial request using Windows Authentication?

I'm working on a web application that has a video page and a Web API for logging purposes. The events are triggered using an ajax post request: function logAction(actionToLog) { $.ajax({ type: 'POST', url: "/api/v/" + cu ...

I'm having trouble making a Javascript ajax request to my Web API controller page. It seems like I just can't figure out the correct URL

Currently, I am facing an issue with my registration page where I am attempting to save input fields into a new record in the Users table. <button class="btn-u" type="submit" onclick="submitclicked()">Register</button> The click event trigger ...

Utilize JSON Objects rather than JSON arrays when using JSON-SERVER

Currently, I am utilizing json-server to transform JSON data into a REST API. Whenever a GET request is made like this: http://localhost:3000/items?itemid=534 The server responds with: [ { "itemid": 534, "type": "textcontent", "icon": "ht ...

Utilizing NPM configuration variables across different operating systems (Windows and Linux): A comprehensive guide

When you use the syntax npm_package_config_<variable>, its usage varies depending on the operating system. In package.json (for Linux & Windows) config: { foo: "bar" } Then for usage: On Linux node app.js --arg=$npm_package_config_foo On Wi ...