The overall outcome determined by the score in JavaScript

Currently, I am working with a dataset where each person is matched with specific shopping items they have purchased. For instance, Joe bought Apples and Grapes.

To gather this information, individuals need to indicate whether they have made a purchase. I typically ask, "Did you buy something? (Apples, Grapes, etc)" and provide Radio Button Options for "Yes" or "No".

If Bob confirms he bought Apples but not Grapes, I aim to derive an overall response for Bob. The final answer should be "Yes," as he did make a purchase.

Here is the code snippet I have been using:

exports.getOverallAnswer = function(boughtSomething){
  var answer = ["Yes", "No"];
  var scores = [5,4];
  var highScore = Math.max.apply(Math,scores);
  var scoreIndex = scores.indexOf(highScore);
  var answerName = answer[scoreIndex];
  return answer;
};

I am struggling to integrate this code with the values of apples and grapes attributed to each individual. Any assistance on how to accomplish this would be greatly appreciated! Thank you in advance!

Answer №1

Utilizing boolean values in this scenario can be incredibly beneficial as they provide a clear true or false response.

A person object can be equipped with various checks as shown below:

Bob.boughtGrapes = false;
Bob.boughtApples = true;

Subsequently, a function can be implemented to determine if the person object has made a purchase:

function checkPurchase(Person person) {
     $result = false;
     if (person.boughtGrapes === true)
          $result = true;
     if (person.boughtApple === true)
          $result = true;
     ......
     return $result;
}

In addition to boolean values, other options such as number values and string values are also viable:

Bob.boughtGrapes = 2; //1 = "Yes", 2 = "No", 3 = "Maybe", etc.
Bob.boughtGrapes = "Yes";
Bob.boughtApples = "No";
Bob.boughtPears = "Maybe";

It is recommended to avoid using string values due to potential spelling errors that could lead to program malfunctions.

Now, the decision can be made on whether "Maybe" will trigger a positive response of "Yes, this person has bought something":

function checkPurchase(Person person) {
     $result = "No"; //Start with a negative answer by default.
     if (person.boughtGrapes === "Yes" || person.boughtGrapes === "Maybe")
          $result = "Yes";
     if (person.boughtApples === "Yes" || person.boughtApples === "Maybe")
          $result = "Yes";
     ......
     return $result; //Returns "Yes" for success, "No" otherwise.
}

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

Troubleshooting GLSL scripts within a web-based WebGL environment

Are there ways to debug GLSL code or display variable values directly from within the GLSL code when using it with WebGL? Does three.js or scene.js offer any features for this purpose? ...

What is the best way to transfer the http server variable between different layers in node.js without requiring it in a separate file?

I've developed a nodeJS application that involves creating a server in the file server.js. The code looks like this: http.createServer(app).listen(app.get('port'), function (err) { if (err) { console.error(err); } else { ...

Preventing Users from Uploading Anything Other than PDFs with Vue

I am currently working with Bootstrap-Vue and Vue2. Utilizing the Form File Input, I want to enable users to upload files, but specifically in PDF format. To achieve this, I have included accept="application/pdf": <b-form-file v-model=&quo ...

[Protractor][Internet Explorer 11]-->I am facing an issue where clicking on a link does not open a new tab even though I have configured the IE browser settings properly

For example: ele.click(); is able to open a new tab in Chrome and Firefox, but not in IE11. However, if I manually click the link, it will open a new tab in IE11. Can someone explain why this is happening? What steps should I take to resolve it? Thank y ...

When a new element is introduced, onmouseenter feature assigns a unique dynamic function variable

I am incorporating elements generated by Javascript using a for loop. My goal is to pass different variables to a function for each element. Check out my code snippet: var thumbnail_box = document.createElement("div"); thumbnail_box.onmouseenter = functi ...

Easily toggle between various image source paths

In my current application, all HTML files have hardcoded relative image paths that point to a specific directory. For example: <img src="projectA/style/images/Preferences.png"/> Now, I am considering switching between two different project modes: & ...

Access denial encountered when attempting to submit upload in IE8 using JavaScript

When running the submit function on IE8, I am receiving an "access is denied" error (it works fine on Chrome and Firefox for IE versions above 8): var iframe = this._createIframe(id); var form = this._createForm(iframe, params); ... ... ...

Having trouble retrieving the chosen option from the select elements

Below is a portion of the code that I have written to capture the selected values of class code and section from a dropdown menu. Currently, only the first element of the select is being retrieved instead of the chosen element. HTML Code: <div id="dia ...

Text area containing an unspecified value within a webpage featuring interactive forms

I'm struggling to understand why I can't access the field values on forms that are generated dynamically through AJAX and MySQL. The structure of the form template is as follows: <form class="dishform" id='" + d.dish_id + "FF' acti ...

Tips for transitioning the li class from active to none

Struggling with changing the li class (of Home) from 'active' to none (or another class) when clicking on the profile tab, and then changing the li class (of Profile) from none to 'active' when the profile is activated. Snippet of my c ...

A guide on utilizing webpack devServer proxy within a create react app

Currently, I am in the process of developing a new application with create-react-app and I am looking to incorporate some proxies into my code. In the past, I utilized webpack's devServer for this purpose. module.exports = { ... devServer: { ...

purging data from javascript objects

In my Node.js HTTP server, I am using 'connect' to build a web service that currently parses JSON requests into an Object, performs operations, and returns a synchronous response. The JSON data comes from an ecommerce cart and results in an Objec ...

Generate a Calendar Table using JavaScript in the Document Object Model (DOM

I have set up a table with 6 rows and 5 columns. The purpose of the table is to represent each month, which may have varying numbers of days. I want each column to display dates ranging from 1-30 or 1-31, depending on the specific month. Here's what ...

Angular setPristine function is not functioning properly

I am looking to achieve a simple task - cleaning the $scope.user fields without encountering errors. if ($scope.contactForm.$valid) { $scope.user = {}; $scope.contactForm.$setPristine(); } However, I'm still experiencing v ...

Determine if a mobile application has been installed using Vue.js

I am currently developing a web application and have implemented a check to determine whether the user is accessing it from a mobile device or laptop. Let's consider the link as: my-site.com In addition to the web version, my site also offers a mobi ...

JavaScript Variables Lose Their Values

Similar Inquiry: How can I get the response from an AJAX call in a function? I have written a function that fetches numerical data from an online file. Although the file retrieval is successful (verified by the alert message), I encounter an issue whe ...

You cannot make a hook call within the body of a function component, unless you are using useNavigate and useEffect in conjunction with axios interceptors

Currently, I am delving into React and attempting to include a Bearer token for private API calls. My approach involves writing a private axios function to intercept requests and responses. Subsequently, I invoke it in my API.js file to fetch data from the ...

How do RxJS collection keys compare?

Is there a more efficient way to compare two arrays in RxJS? Let's say we have two separate arrays of objects. For example: A1: [{ name: 'Sue', age: 25 }, { name: 'Joe', age: 30 }, { name: 'Frank', age: 25 }, { name: & ...

Steps for displaying a loading image during the rendering of a drop-down list (but not during data loading):

Using jQuery's autocomplete combobox with a large dataset of around 1,000 items. The data loads smoothly from the server, but there is a delay when expanding the drop-down list to render on screen. Is there a way to capture the initial click event on ...

Bug in timezone calculation on Internet Explorer 11

I've spent hours researching the issue but haven't been able to find any effective workarounds or solutions. In our Angular 7+ application, we are using a timezone interceptor that is defined as follows: import { HttpInterceptor, HttpRequest, H ...