What steps can I take to enhance the efficiency of this JavaScript DOM data manipulation algorithm?

Purpose

I am working with a DOM that contains around 70 elements (divs with content). I have the need to move and toggle the display of these divs frequently and rapidly. Speed is crucial in this process. The trigger for moving and toggling these divs is a search query, similar to Google Instant, but all the DOM elements are loaded initially without any server calls.

Approach

The approach I have taken involves passing a JavaScript array of objects along with the DOM. This array mirrors the structure of the DOM elements including their attributes like position and content. When a user starts typing, I iterate through this array multiple times to determine the actions needed for each div/object. To optimize performance, I minimize direct interaction with the DOM as much as possible since manipulating the DOM is slower compared to other operations like looping and attribute manipulation. Finally, after making all the necessary calculations, I perform the required DOM actions using jQuery for cross-browser compatibility.

Challenge

Currently, my code and data structure feel somewhat cumbersome. The multidimensional array containing various attributes and flags makes it complex. Debugging is manageable, but the overall structure doesn't seem elegant.

Inquiry

Is there a design pattern or solution that could streamline this process? I believe implementing a smart relationship between the array and the DOM might eliminate the need for explicit flag setting and DOM actions. However, I'm unsure about how to establish such a connection effectively and whether it would complicate the system further.

Are there any overlooked data structure or algorithmic principles that could simplify this problem-solving process?

Thank you!

Update As requested, here is a snippet of my code which spans approximately 700 lines. Please note that these functions are enclosed within a closure scope and do not pollute the global namespace.

...
(JavaScript code continues)
...

Answer №1

Great job with the well-commented and nicely formatted JavaScript code!

Initially, it appears that utilizing a SQL database query would be more suitable for your specific use case. Querying a database to retrieve category IDs and locations might be more efficient than your current approach. It seems like you may be handling everything on the client side due to limited access to a database, static data, or concerns about real-time database performance.

To optimize your current implementation, consider lowercase and concatenate all Link data properties into a single property in advance.

function linkMatches(link, query) {
    if (link["ConcatenatedLCasedProperties"].indexOf(query) !== -1) {
        return true;
    }
    return false;
}

UPDATE Here is an improved and faster version of your divideInPiles function.

function divideInPiles(items, piles) {
    var result = [];
    var perPile = Math.floor(items / piles);
    var leftOver = items % piles;
    if (piles == 0)
        return false;
    for (var x = 0; x < piles; x++)
        result.push(perPile + (--leftOver >= 0 ? 1 : 0));
    return result;
}

Answer №2

In my opinion, utilizing a tree structure could be a viable option in this scenario. Additionally, experimenting with various graph algorithms may also prove to be beneficial. It might be worth considering incorporating hidden div elements at each level of the tree to store pertinent information, which can then be easily displayed when needed without directly manipulating the div content.

However, it is crucial to define your task with more specificity. Real-life examples would greatly enhance understanding and implementation.

Answer №3

To minimize the cost of DOM operations, it is recommended to detach elements from the tree, perform any necessary work on them, and then reattach them back to the DOM. One convenient way to do this is by using JQuery's .detach() method.

Although I am not familiar with your specific data structure, keep in mind that plain loops with counters are usually the fastest option. Make sure to store any length values in variables to avoid unnecessary lookups during each iteration.

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

Obtaining JSON information within the AngularJS Scope

I am delving into the world of AngularJS for the first time and trying to understand it by following this example: http://jsfiddle.net/SAWsA/11/ After successfully acquiring data in JSON format, I encountered no issues. Here is a snippet of the JSON data: ...

Transfer the file image stored in a MySQL database to an excel spreadsheet

Having an issue with capturing image data input from a PHP and HTML database to Excel. I am trying to display the images in a specific size within an Excel file. Below is the PHP code used to create the table: <?php header("Content-type: application/o ...

The text box's word limiter is malfunctioning when writing code on a child page of the master

Encountering an unexpected problem that I never thought would happen. I wrote a word limiter code for a text box on a single page and it was working perfectly fine. The word limiter worked and the remaining words were displayed by a label named "remaining6 ...

Issues with the functionality of jQuery's .load() method are causing

I am encountering an issue for the first time. Inside ajax.html, I have the following code in the header: $(document).ready(function(){ $( "#result" ).load( "/loaded.html" ); }); In the same directory, there is a second page named loaded.html: <d ...

Contrasting bracket notation property access with Pick utility in TypeScript

I have a layout similar to this export type CameraProps = Omit<React.HTMLProps<HTMLVideoElement>, "ref"> & { audio?: boolean; audioConstraints?: MediaStreamConstraints["audio"]; mirrored?: boolean; screenshotFormat?: "i ...

Issue with Material UI select component not displaying the label text

I've been struggling with Material UI's "Select" for quite some time now - spent about 10 hours trying to make it work the way I want. Any help would be greatly appreciated. This question is connected to a previous one: Select MenuItem doesn' ...

Sometimes the Navbar options fail to show up consistently on the Navbar bar

I recently launched my website at campusconnect.cc Unfortunately, I've noticed that when resizing the window, the navbar options are shifting up and down. Can anyone help me identify the issue and provide guidance on how to resolve it? ...

The inner HTML functionality in Angular 2 seems to be malfunctioning when dealing with HTML tags

I am facing an issue with an array that includes displayName with HTML tags: this.topicsList = [ {id: "173", name: "Discussion1", displayName: "Discussion1", status: 1}, {id: "174", name: "discussion123", displayName: "discussion123", status: 1}, {id: "19 ...

Tips on transforming JSON data into a hierarchical/tree structure with javascript/angularJS

[ {"id":1,"countryname":"India","zoneid":"1","countryid":"1","zonename":"South","stateid":"1","zid":"1","statename":"Karnataka"}, {"id":1,"countryname":"India","zoneid":"1","countryid":"1","zonename":"South","stateid":"2","zid":"1","s ...

Different approach to iterating through elements

Looking to implement .forEach instead of a traditional for loop? 'use strict'; var score = (function(){ function updateScore() { for(var i = 0; i < arguments.length; i++) { this.score += arguments[i]; ...

Encountering a React Runtime issue: The element type is invalid, expecting a string for built-in components or a class/function for composite components

Here is a glimpse of my code: import { React, useState, useEffect } from 'react'; import { GoogleMapReact } from 'google-map-react'; import styles from './Location.module.scss'; import pinstyles from './TheMap.module.scss ...

How come the mongoose ref feature is not functioning properly for me when I attempt to reference objects from a different schema?

I'm having trouble accessing the attributes of a store's address, as I keep getting 'undefined'. It seems that the address is only an id, even though I set up a 'ref' in the address schema. What could be causing this issue? H ...

Tried to enroll the RCTBridgeModule category as RCTFileReaderModule

Trying to register the RCTBridgeModule class RCTFileReaderModule with the name 'FileReaderModule' failed because the name was already taken by the FileReaderModule class. This issue arises when attempting to launch an application on iOS using th ...

Fixing Laravel 5.2 and jQuery validation issue: Accessing a property from a Non-Object

Currently, I am utilizing the jQuery validation plugin to check whether a username already exists or not. The documentation regarding the validation plugin states: The server-side resource is accessed through jQuery.ajax (XMLHttpRequest) and receives k ...

Using jQuery UI datepicker - how to set a parameter based on a specific condition

New to the world of JavaScript, I am trying my hand at implementing the jQuery UI datepicker widget. My goal is to add an additional line to the widget parameters if the variable selectedDate has a value. However, my current approach seems to be ineffecti ...

What steps do you need to take in order to transform this individual slideshow script into numerous slideshows

I came across this code online that effectively creates a slideshow. https://css-tricks.com/snippets/jquery/simple-auto-playing-slideshow/ Is there a way to modify the code to support multiple slideshows? I've made several attempts without success ...

Upgrading to NPM version 7 or higher: A guide to effectively installing packages using the "lockfileVersion" parameter: 1

After upgrading NodeJS to version 16, I noticed that NPM version 8 is now included. This means that when I install packages, the package-lock.json file is generated with a "lockfileVersion": 2. However, I prefer the older format of "lockfileVersion": 1. ...

Results don't align with search parameters

const searchClientes = (event) => { if (event.target.value === '') { getClientes(); return; } else { const searchTerm = event.target.value; const filteredClients = clientes.filter(cliente => { return cliente.nome ...

Understanding the time complexity of Object.entries()

Is the complexity of Object.entries() in JavaScript known? According to information from this question, it seems like it could possibly be O(n) if implemented by collecting keys and values as arrays and then combining them together? ...

Hey there, could you please set up the DateTimePicker in my expo project using React Native?

Hey everyone, I'm currently trying to set up DateTimePicker but encountered an error. Here's the issue: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: undefined@undefined npm ERR! Fou ...