Is there a more concise way to simplify the code in Node.js Express?

Looking to optimize the following code by using variables in a for loop. Is it possible to do this in Node.js?

function hasPortion(meals) {
const portions = ["4", "3", "2", "1", "1/8", "1/4", "1/2"];
for (let i = 1; i <= 10; i++) {
if (meals[`meal${i}`] != undefined && meals[`meal${i}`].activado == "on" && portions.indexOf(meals[`meal${i}`].porcion) < 0) { return false; }
}
return true;

}

Answer №1

If you are looking to check if meals have specific properties, the following function may be useful:

function hasPortion(meals) {
    const portions = ["4", "3", "2", "1", "1/8", "1/4", "1/2"];
    for (const prop in meals) {
        const meal = meals[prop];
        if (meal != undefined && meal.activado == "on" && portions.indexOf(meal.porcion) < 0) {
            return false;
        }
    }
    return true;
}

If you have more properties but only want to focus on checking these 10 properties, consider using this alternative approach:

function hasPortion(meals) {
    const portions = ["4", "3", "2", "1", "1/8", "1/4", "1/2"];
    for (let i = 1; i <= 10; i++) {
        const prop = `meal${i}`;
        const meal = meals[prop];
        if (meal != undefined && meal.activado == "on" && portions.indexOf(meal.porcion) < 0) {
            return false;
        }
    }
    return true;
}

New solution suggestion:

Consider utilizing an Array to store all meal items and a Set to store portions for efficient searching.

const meals = [
    { activado: "on", porcion: "4" },
    { activado: "on", porcion: "1/8" },
    { activado: "on", porcion: "3" },
    { activado: "on", porcion: "1/2" },
];

function hasPortion(meals) {
    const portions = new Set(["4", "3", "2", "1", "1/8", "1/4", "1/2"]);
    return !meals.some((meal) => meal.activado === "on" && !portions.has(meal.porcion));
}

// Example usage
console.log(hasPortion(meals));                // Output: true
// Add a non-matching item
meals.push({ activado: "on", porcion: "1/3" })
console.log(hasPortion(meals));                // Output: false

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

Employing a $_POST array in conjunction with database records

Is there a way to add each item in the $_POST array to every database row I have? My form has multiple fields, but only one can be changed by the user - the quantity. The rows in this field are identical to the ones used in the PHP file (in order). I&apo ...

Organizing the Outcomes of an Array

After a successful ajax request, I receive an array that contains information about various locations. Here is how the array looks: List of Locations: [{ "locationID": "9", "locationName": "Employee Residenc ...

Angular binding and date validation - a powerful combination!

Facing an issue with date properties in Angular. For instance, here is the Model I am working with: export class Model{ dateFrom Date; dateTo Date; } In my Create view, I have the following setup: <input type="date" [(ngModel)] = "model.dateFrom"> ...

Executing a JavaScript function within a PHP echo statement

I am completely new to working with AJAX and PHP echo variables or arrays. However, I have managed to successfully display images on my website by passing variables from AJAX to PHP and back. The only problem I am encountering is when I try to call a Javas ...

Leveraging @click within dropdown selections - Vue.js 2

Is there a way to implement the @click event in select options? Currently, I have the following: <button @click="sortBy('name')">sort by name</button> <button @click="sortBy('price')">sort by price</button> Th ...

Showcase an Array on an HTML page using EJS

When a user posts an object on my website forum using Ejs/NodeJs/MongoDb, it creates a new object with properties like title, comment, and reply array. I have successfully displayed the titles and comments in different HTML elements, but I am facing an i ...

React date format error: RangeError - Time value is invalid

I'm utilizing a date in my React app using the following code: const messageDate = new Date(Date.parse(createdDate)) const options = { month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric' } as const ...

What is the reason for the unique behavior of v-bind with boolean attributes? More specifically, why is the number 0 considered truthy in

According to the official documentation, <button v-bind:disabled="isButtonDisabled">Button</button> In this example, the disabled attribute will be added if isButtonDisabled is equal to 0, despite the fact that in JavaScript, 0 is co ...

extracting ng-repeat values and passing them to the controller

I have created a form that dynamically increases whenever the user clicks on the add sale button Here is the HTML code: <fieldset data-ng-repeat="choice in choices"> <div class="form-group"> <label for="name"> Qu ...

Using JavaScript, reload the page once the data has been retrieved from an Excel spreadsheet

I'm facing an issue with my JavaScript code. Here's what I have: a = Excel.Workbooks.open("C:/work/ind12.xls").ActiveSheet.Cells.find("value"); if(a == null) document.getElementById('dateV ...

What is the average time frame for completing the construction of an electron project?

My project has only a few npm dependencies, but the build process is taking longer than 30 minutes and still counting. I'm not sure if this is normal or if there's an issue causing the delay. I have two specific questions: Is it common for pro ...

Creating an array of objects using the NSArray class

As someone who is relatively new to Objective-C and iOS development, I've been experimenting with the Picker View feature. One interesting thing I did was define a Person Class that automatically assigns a name and age to each newly created Person obj ...

Preventing all hammer.js (angular-hammer) interactions except for single taps

Utilizing the angular-hammer module in my app, I am keen on refining its performance specifically for the tap event. Given that no other gestures are required, I aim to enhance efficiency by excluding unnecessary listening functions, such as double tap. As ...

Using flags to translate text on Google should not result in being redirected to another website

I have integrated Google's language picker with country flags into my WordPress template using the code below: <!-- Add English to Chinese (Simplified) BETA --> <a target="_blank" rel="nofollow" onclick="window.open('http://www.google. ...

If I include the '=' symbol with the request value, the request params will be null

I am currently working on a node.js project that utilizes the express framework. The main purpose of my application is to handle multiple POST requests. One of these POST requests is as follows: URL POST /processit request params info={"one":"a=5"} n ...

Can you explain the process that takes place when require("http").Server() is called with an Express application passed in as a parameter?

As I was exploring the Socket.io Chat Demo found at this link: http://socket.io/get-started/chat/, I came across their require statements which left me feeling confused. var app = require('express')(); var http = require('http').Server ...

The fitBounds() method in Google Maps API V3 is extremely helpful for adjusting

I am trying to display a map on my website using this code: function initialize() { var myOptions = { center: new google.maps.LatLng(45.4555729, 9.169236), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP, panControl: true, mapTyp ...

Trigger Vue to scroll an element into view once it becomes visible

I created a dynamic form that calculates 2 values and displays the result card only after all values are filled and submitted, utilizing the v-if directive. Vuetify is my chosen UI framework for this project. This is the approach I took: <template> ...

Creating unique parent-children category groupings in Excel VBA using collections and dictionaries - how can it be done?

Could someone assist me in understanding how to consolidate data by hierarchical groupings using VBA? PivotTables and tables are not feasible due to user constraints. The data includes three levels of groupings: Parent, Child, and Grain. Parents may have ...

Constructing an upload functionality with the help of "A touch of vanilla framework"

After reading through this article, I decided to try my hand at creating a file upload using XMLHttpRequest. My approach was to start by using the code provided in the document's A little vanilla framework section. Once I got it working on my own sit ...