Using if/else statements inside the reduce function is causing a delay in the processing time

My Vue app has a reduce function that, while logically sound, is running incredibly slow.

After some experimentation, I realized that the bottleneck lies in the if/else statement at the bottom of the function, especially when dealing with large datasets. Removing this section significantly speeds up the operation.

Should I move the problematic portion into a separate function and call it at the end of the reduce process? Or is there a more efficient approach that I'm overlooking to maintain cleanliness and functionality?

Answer №1

It's highly likely that the performance bottleneck lies with the find() function rather than the if statement.

To optimize, consider creating a Set containing all heir identifiers to swiftly verify the existence of the current identifier.

const enhanceEfficiency = (rows) => {
  let heirs = new Set(vm.$data.kitsData.map(kit => kit.heir_identifier));
  return rows.reduce(
    (a, row) => {
      const employee = a[row.employee] || (a[row.employee] = {
        dates: {},
        total_categories: 0,
        total_items: 0,
        area: '',
        group: ''
      })
      const date = employee.dates[row.itemDate] || (employee.dates[row.itemDate] = {
        categories: 0,
        qty: 0,
        total_categories: 0,
        unavailable: 0,
        orders: {}
      })

      date.categories += +row.categories_per_item * +row.qty
      date.qty += +row.qty

      date.total_categories = date.categories

      const order = date.orders[row.order_number] || (date.orders[row.order_number] = {
        itemDate: '',
        skus: {}
      })

      order.itemDate = row.itemDate;

      const sku = order.skus[row.sku] || (order.skus[row.sku] = {
        categories: '',
        qty: '',
        itemDate: '',
        expected: '',
        created: '',
        unavailable: 0,
        available: 0
      })

      sku.categories += row.categories_per_item
      sku.qty += row.qty
      sku.itemDate = row.itemDate
      sku.expected = row.shipDate
      sku.created = row.created_date
      sku.heir_id = row.heir_identifier

      employee.total_categories += (+row.categories_per_item * +row.qty)
      employee.total_items += (+row.qty)
      employee.area = row.area
      employee.group = row.group_name
      employee.warehouse = row.warehouse
      employee.locale = row.locale

      if (heirs.has(sku.heir_id) {

          new_avail = 10;

          if (sku.qty > new_avail) {
            status.status = "Not available";
            date.unavailable += 1
            sku.unavailable += 1
          } else {
            status.status = "Available"
          }
        } else {
          status.status = "No item found"
        }

        return a
      }, {}
    )
  }
};


var vm =
  new Vue({
    el: "#app",

    data: {
      rows: [{
          employee: "Adam",
          sku: "A1453",
          categories_per_item: "15",
          area: "1",
          itemDate: "2021-11-02",
          qty: 37,
          group_name: "managers",
          warehouse: "3",
          order_number: "1234",
          locale: "1",
          shipDate: "2020-02-02",
          created_date: "2020-01-01",
          heir_identifier: "ABC3"
        },
        {
          employee: "Joan",
          sku: "A1453",
          categories_per_item: "15",
          area: "1a",
          itemDate: "2021-11-02",
          qty: 17,
          group_name: "managers",
          warehouse: "3",
          order_number: "34578",
          locale: "1",
          shipDate: "2020-02-02",
          created_date: "2020-01-01",
          heir_identifier: "ABC3"
        },
        {
          employee: "Bill",
          sku: "A1453",
          categories_per_item: "15",
          area: "1",
          itemDate: "2021-11-03",
          qty: 57,
          group_name: "managers",
          warehouse: "3",
          order_number: "2345",
          locale: "1",
          shipDate: "2020-02-02",
          created_date: "2020-01-01",
          heir_identifier: "ABC3"
        },
        {
          employee: "PJ",
          sku: "A6512",
          categories_per_item: "150",
          area: "2",
          itemDate: "2021-11-03",
          qty: 20,
          group_name: "managers",
          warehouse: "3",
          order_number: "34567",
          locale: "1",
          shipDate: "2020-02-02",
          created_date: "2020-01-01",
          heir_identifier: "ABC1"
        }
      ]
    },
    methods: {

    },

    computed: {
      employeeData() {
        console.log('employee data')
        employeeRows = reduceFunction(this.rows)
        return employeeRows
        console.log(employeeRows)
      },

      dates() {
        return Array.from(Array(11), (_, i) => new Date(Date.now() + i * 86400000).toISOString().slice(0, 10))
      }

    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <tr v-for="(value, employee) in employeeData" :key="employee">
    <td>@{{employee}}</td>
    <td v-for="date in dates" :key="date">
      <div v-for="(dateInfo, dateValue) in value.dates" :key="dateValue">
        <div v-if="dateValue == date ">

          @{{ dateInfo.total_categories }}

        </div>
      </div>
    </td>
  </tr>
</div>

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

Is there an issue with the precedence of jison rules?

I've been stuck for hours trying to solve what seems like a simple problem but I just can't figure it out :/ I'm working on defining a small javascript-like language in jison. The issue I'm facing is that both the Parameter rule and th ...

Is there a way to create dynamic documents in Firestore using Angular?

How can I use a dynamic ID to fetch the values of a document in Firestore? For example, if I have documents named document1 and document2 under the same collection, how can I specify a dynamic path with a dynamic document name to retrieve the specific do ...

Transferring information from a service to an AngularJS controller

I have a service that retrieves data from a URL provided as a parameter, and it is functioning correctly. However, when attempting to pass this data to a controller's $scope in AngularJS, I am not receiving any data. var app = angular.module("Recib ...

Model for handling Node/Express requests

I always saw Node.js/Express.js route handlers as akin to client-side EventListeners such as onClick, onHover, and so on. For example: document .getElementById('btn') .addEventListener('click', function() { setTimeout(functi ...

What are some ways to implement AJAX with input from the user?

I'm currently working on a project to create a basic web page that will make use of AJAX for displaying results. Within main.py, I have a dictionary of words: words = { 'a': True, 'aah': True, 'aahed': True, ...

`How to implement a dark mode feature in Tailwind CSS with Next.js and styled-jsx`

My website is created using Next.js and Tailwind CSS. I followed the default setup instructions to add them to my project. In order to style links without adding inline classes to each one, I also integrated styled-jsx-plugin-postcss along with styled-jsx ...

Choose the specific selector following the current selector

Consider this example of code: <script> $(document).ready(function () { $('span').each(function () { $(this).html('<div></div>') ; if ( $(this).attr('id') == 'W0' ...

How can we develop a strategy to select products based on specific features while keeping costs minimized?

I've got a collection of products with varying costs and features. Each product offers a unique set of features. I'm in need of an algorithm that, when given the specific features I desire, can recommend the most cost-effective combination of pr ...

Testing multiple regex patterns using jQuery

I am attempting to run multiple regex tests on an input field. Here is the script: $("#search-registration").keyup(function () { var input_data = $('#search-registration').val(); var regexTest = function() { this.withPrefix = /^ ...

The incorporation of ASP.NET with Cors cookies enhances security and functionality

Currently, I am utilizing an MVC server with IIS express running on port x. My client code is executed using an express server on port y, and requests for data are sent to the server located at localhost:x. An issue arises as the SessionId cookie is not c ...

Use jQuery to collapse all of the child elements that are currently expanded under a specific parent element

In my list order, I have multiple levels nested within each other: <ul> <li>level 1 a <ul> <li>level 2 a <ul> <li>level 3 a</li> < ...

Exploring the method of retrieving a wrapped object's property within a Node.js addon

Currently, I am dealing with the following JavaScript code snippet: var c = new addon.Component(); c.ComponentLength = 3 I am struggling to figure out how to structure my addon in order to execute the above code successfully. I have already gone through ...

Having trouble with iterating through nested array objects in Angular 4 component

I am facing an issue when attempting to iterate over a nested array object using the code below. It seems to be throwing an error saying "undefined". Could this be related to Typescript or angular4? import { Process, Event } from "./process"; export clas ...

troubleshooting Axios errors in React applications

User/Project.js: import React, { useState, useEffect } from "react"; import Axios from "axios"; const Project = () => { const [projectName, setprojectName] = useState(""); const [projectDescription, setprojectDescriptio ...

Choosing a particular 2D array based on another variable in jQuery and JavaScript

Within my project, I am utilizing 2D arrays to append specific divs under particular circumstances. In an effort to streamline and enhance the code, I attempted to create a variable that would determine which array to utilize based on the id of an HTML < ...

Is there an issue with Three.js canvas.toDataURL() function in Chromium browsers?

After performing a recent system upgrade, I noticed some issues with Chromium. One of them was a delay in loading my Three.js r85 project, which was resolved after upgrading to Three.js r90. However, I encountered a new problem with toDataUrl() not workin ...

What is the best way to refresh data in a React component so that it displays the recently added data?

My website features a todo list that functions like this: Todo list Upon clicking the plus button, an input field appears allowing users to add items. Although the item is successfully added to the database, it does not immediately reflect on the webpage ...

What could be causing the error? And is there a way to successfully append the child div to the parent div?

Here is the error message that I am encountering: Uncaught TypeError: Cannot read property 'appendChild' of null at HTMLButtonElement.<anonymous> Error is located at app.js on line 7 const flexContainer = document.querySelector(&apo ...

The Route.get() function in Node.js is expecting a callback function, but instead received an unexpected object of type

Recently, I started coding with nodejs and express. In my file test.js located in the routes folder, I have written the following code: const express = require('express'); const router = new express.Router(); router.get('/test', (req ...

Filtering Tables with AngularJS

Currently, I'm experimenting with using angularJS to filter data in a table. My goal is to load the data from a JSON file that has a structure like this (example file): [{name: "Moroni", age: 50}, {name: "Tiancum", age: 43}, { ...