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

Angular Translate - Utilizing translate-values attribute for translation

Having trouble using angular translate with dynamic translation values that need to be translated first. If you want a better explanation of the issue, check out this plunker: PLUNKER <p translate="PARAGRAPH" translate-values="{username: ('us ...

Avoiding a constantly repeating video to prevent the browser from running out of memory

Using HTML5, I created a video that loops and draws the frames to canvas. I decided to create multiple canvases and draw different parts of the video on each one. However, after some time, I encountered an issue where Google Chrome would run out of memory. ...

Altering the "src" property of the <script> tag

Can the "src" attribute of a current <script> element be altered using Jquery.attr()? I believed it would be an easy method to enable JSONP functionality, however, I am encountering difficulties in making it operate effectively. ...

What is the best way to transfer a property-handling function to a container?

One of the main classes in my codebase is the ParentComponent export class ParentComponent extends React.Component<IParentComponentProps, any> { constructor(props: IParentComponent Props) { super(props); this.state = { shouldResetFoc ...

Closing a live search box by tapping away from it

The link I found as the best example for this topic is: http://www.example.com In the example provided, if you enter a keyword in the search field, suggestions will drop down. I have implemented this code but would like to make a slight modification. I w ...

Storing client time data in a database using Node.js

Just starting out with Node.js so bear with me while I learn the ropes. I successfully set up a basic TCP server using the guide here In my current project, users will connect to the server from a web browser and I'm interested in capturing the TCP ...

Create a duplicate of the table and remove specific rows

Hi there, I have a query about duplicating a table. I am looking to extract specific results and display only those results. To illustrate, here is an example in HTML code: <table class="table table-striped" id="ProfileList2"> <tbody> ...

Are there any jQuery plugins available that animate elements as the page is scrolled?

Looking for a library that can create entry animations for elements as the page is scrolled? I previously used the animate it library, which was great - lightweight and easy to use. However, it doesn't seem compatible with the latest jQuery version (3 ...

Exploring sagas: Faking a response using a call effect

In my current scenario, I am facing a challenging situation: export function* getPosts() { try { const response = yield call(apiCall); yield put({ type: "API_CALL_SUCCESS", response }); } catch(e) { // ... } Furthermore, there is a spec ...

Communicating between PHP chat client and server

Currently, I am developing a basic PHP web chat application that interacts with a MySQL database. The communication is facilitated through AJAX requests - when a user posts a message, it gets saved in the database. function sendData(){ var textData = $(& ...

Tips for effectively utilizing the updateAxisPointer function in the latest version of vue-echarts (v4.1)

Version 3 allows for direct use of the echarts functions and events, with the ability to override event functions like const updateAxisPointer = function(event)... However, I am struggling to implement this in version 4. You can find more information about ...

Struggling to parse the JSON blob that was returned when using express-handlebars in node.js? Let

I am in the process of learning node.js and following a tutorial that involves making requests to the Accuweather API and receiving JSON data. Almost there ... but struggling with displaying the data: index.js const express = require('express' ...

"Utilizing JSON parsing in Node.js and rendering the data in a Jade template

I need assistance with parsing JSON and presenting the response in a tabular format using Jade. Can you help me display the key-value pairs in two separate columns? Node.js exports.postMQinput = function(req, res) { req.assert('name', 'Q ...

How can you generate a Ref in React without utilizing the constructor by using React.createRef?

In the past, I relied on using constructor in React for just three specific purposes: 1. Initializing state as shown below: class App extends React.Component { constructor(props) { super(props); this.state = { counter: 0 }; } } H ...

Transferring data from a database on Express back-end to a React front-end

I am facing an issue while trying to display user information on the front-end. Even though I can access the server using localhost:8080/api/user and see the information in the form of an empty page, my content page is unable to render this data. The code ...

A guide to retrieving nested values from a JSON object using JavaScript

Having trouble accessing specific values from a heavily nested JSON content returned by a URL? You're not alone! Many tutorials only cover simple nesting examples. Take a look at the code snippet I've been working on: $(document).ready(function ...

Utilize JQuery's .load() function to transmit JSON data to your Flask server

I am attempting to utilize JQuery's .load() function in order to transmit data to my Flask server and then, with that information, display a <div> that is loaded into the element making the request. This is what my code snippet looks like: $(&qu ...

What is the best way to retrieve a value from a database and display it in a radio

Can you help me figure out how to implement this functionality? I have a database with a "boolean" field that stores 0 or 1 values. On an HTML page, there is a radioButton with options for OK or NO. I need to dynamically load the boolean value from the dat ...

What is the ideal way to utilize Vue within the framework of multiple pages?

When using the default Vue CLI setup, Vue is loaded from the index.html page. To work with Vue and dynamic content on the page, everything is typically handled in the App.vue file. But what if you want to make significant layout changes to the page? How d ...

Encountered a build issue following the Svelte update: The subpath package './compiler.js' is not recognized by the "exports" definition

Challenge After updating from Svelte version 3.0.0 to the latest using npm i svelte@latest, I encountered an issue where my application would not run and constantly displayed the following error: [!] Error: Package subpath './compiler.js' is n ...