Halt the iteration process and confirm a true result upon discovering a match between two arrays

I have two databases, one stored in indexedDB and the other in PouchDB (even though I am aware that PouchDB is built on top of indexedDB).

The dataset in indexedDB contains a list of rooms, which was saved through a previous page and is now being displayed on the current page.

On the other hand, the database in PouchDB consists of logs detailing the usage of each room recorded by an auditor. My goal is to iterate through the room list in indexedDB and check if each item appears in the audited rooms list. If a match is found, I want to set a flag to indicate this.

Below is my JavaScript code. Although the console log displays "true" at certain points during execution—indicating successful matches—the flag does not get properly set for the corresponding list item.

I am speculating whether the function continues to cycle through the audit records, possibly overwriting the value of "true"?

This snippet requests data from indexedDB and then calls a function to retrieve information from PouchDB:

function getRoomsInRoute() {
    var routeNumber = $.jStorage.get('currentRoute', '');
    var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;

    openRequest = window.indexedDB.open("rooms", 1);
    openRequest.onupgradeneeded = function() {
        var db = openRequest.result;
        var itemStore = db.createObjectStore("rooms", {keyPath: "room_id"});
        var index = itemStore.createIndex("rooms", ["route_number"]);
    };

    openRequest.onerror = function(event) {
        console.error(event);
    };

    // The rest of the JavaScript function...

and here is the accompanying function that interfaces with PouchDB to verify if auditing has been conducted:

function checkIfAudited(roomseq) {
    // Implementation of logic to determine if a room has been audited in PouchDB.
}

I have extensively reviewed multiple questions and responses relating to comparing two arrays.

However, I am uncertain about how to incorporate a for loop within pdb.allDocs.

The output recorded via console.log is as follows:

49 No matches

RoomSeq: 1; auditHour: 14; currentHour: 14; auditDay: 16 currentDay: 16; auditMonth: 0; currentMonth: 0; isAudited: true

2300 No matches

How can I modify the second function to halt and return "true" upon locating a matching record in PouchDB?

Answer №1

Instead of trying to get too creative with taking advantage of the short-circuiting feature of `Array.prototype.some`, stick to using the existing native functionality. indexedDB has its own built-in way to stop a cursor from moving forward or load only a specific number of objects from a store.

It's wise to avoid loading all objects from a store if you're only interested in a few. Utilize a cursor to navigate through the store and stop iterating when a certain condition is met by simply avoiding calling cursor.continue at that point.

If you do end up loading all objects from the store initially, it's more advisable to use a traditional for loop instead of manipulating `some`. Using functions in unintended ways can lead to confusion. Switch back to a for loop with a break statement for clearer code understanding.

Take the extra step to store results of an indexedDB query in an intermediary data structure like an array before directly interacting with the DOM. This segregation will make debugging easier and the code cleaner.

Exercise caution when mixing asynchronous calls with indexedDB as interleaving calls to other promises can cause issues due to known problems associated with indexedDB.

Answer №2

From my perspective, the pouchdb method alldocs operates asynchronously. However, when you test the audit process, it is done synchronously. This results in the callback function returning after the execution of checkIfAudited, causing checkIfAudited to always return undefined.

In my view, a better approach would be to instantiate the pouchdb instance only once in temStore.openCursor().onsuccess. Then, ensure that the audit status is correctly returned within the checkIfAudited function.

Here's an example of how you could modify the code:

itemStore.openCursor().onsuccess = function(event) {

  var cursor = event.target.result;

  if (cursor) {

    if (cursor.value.route_number == routeNumber) {

      var audited;
      options = {},
      pdb = new PouchDB('pouchroomusage');
      options.include_docs = true;

      pdb.allDocs(options, function (error, allDocsResponse) {

        if (checkIfAudited(allDocsResponse, cursor.value.room_seq)) audited = ' <span class="checked"><i class="fa fa-check"></i></span>'

        else audited = "";

        $('#mylist').append("<li id="+ cursor.value.room_id +" rel="+ cursor.value.room_seq +"> " + '<small>'+ cursor.value.room_seq + '.&nbsp;</small><a href="/static?action=edit&amp;room_id='+ cursor.value.room_id +'&amp;route_number='+ cursor.value.route_number +'&amp;sequence='+ cursor.value.room_seq +'&amp;roomname='+ cursor.value.room_name +'&amp;capacity='+ cursor.value.room_capacity +'">' + cursor.value.room_name + '</a>'+audited+'</li> ');

      });

    };

    cursor.continue();

  } else {

    console.log('All entries displayed.');

    if(!($.jStorage.get('reverseroute', ''))) reverseroute = 'asc'

    else reverseroute = $.jStorage.get('reverseroute', '');

    appendHref(reverseroute);

  };


};

As for the checkIfAudited function:

function checkIfAudited(allDocs, roomseq) {


    var today = new Date();
    if(is_BST(today) == true) {
        var currentHour = today.getHours()+1;
    } else {
        var currentHour = today.getHours();
    }
    var currentDay = today.getDate();
    var currentMonth = today.getMonth();

    for (i=0; i<allDocs.rows.length; i++) {
      var row = allDocs.rows[i];

      var auditTime = new Date(row.doc.timestamp);
      var auditHour = auditTime.getUTCHours();
      var auditDay = auditTime.getDate();
      var auditMonth = auditTime.getMonth();
      if(row.doc.sequence == roomseq && currentHour == auditHour && currentDay == auditDay && currentMonth == auditMonth) {
        console.log('RoomSeq: ' + roomseq + '; auditHour: ' + auditHour + '; currentHour: ' + currentHour + '; auditDay: ' + auditDay); 
        console.log('currentDay: ' + currentDay + '; auditMonth: ' + auditMonth + '; currentMonth: ' + currentMonth + '; isAudited: ' + isAudited);
        return true;    ///// <---- return that it is audited
      } else {
        console.log('No matches');
      };

    });

    return false    ///// <---- return false if no iteration has matched
}

Answer №3

After numerous adjustments, this is the final outcome I arrived at.

Each <li> tag now includes

<span class="checked"><i class="fa fa-check"></i></span>
, although it may be added more than once for each item. Nevertheless, it ensures that every <li> contains the necessary content.

To rectify this issue, I implemented a CSS workaround to display only one instance of span.checked:

.checked {
    color: #fff;
    background-color: #006338;
    border-radius: 50%;
    padding: 2px 3px;
}

/* Show only the first checked span */
li > span.checked ~ .checked {
    display: none;
}

(Additionally, I identified and corrected an error in my script relating to setting route_number or room_id.)

function getRoomsInRoute() {
    // Function logic here...
}


function asyncCallToPouchDb() {
    // Function logic here...
}


function callPouchDb(room_id, thisLi) {
    // Function logic here...
}


function checkIfAudited(row, room_id) {
    // Function logic here...
}

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

Guide for saving a byte-list to a file using Python

I am attempting to write a binary file using a list of bytes. The code I have is as follows: Below is the code snippet: import struct as st shellcode = bytearray("\xeb\x1f\x5e\x89\x76\x08\x31"+ "\xc0\x88 ...

What is the process for transferring `Parentobject1` to `childobject2` and `childobject3` in Three.js?

I have created two objects doubleSquare and doubleSquare1. I was expecting the output to be Double Line Square Object, but I have tried two different formats and have not achieved the desired output. Can someone please provide me with a solution? I have lo ...

Encountering an issue while trying to install nodemon on Ubuntu 18.04

After attempting to install nodemon using the command: sudo npm i --save-dev nodemon I encountered the following error message: npm ERR! path /home/dominikpatera/Dropbox/Projekty/Fytwa/server/node_modules/npm/node_modules/abbrev npm ERR! code ENOENT npm ...

What is the method for calling a function in a JavaScript file?

I am facing a challenge with reinitializing a JavaScript file named AppForm.js after a successful ajax post response. Within the file, there are various components: (function(namespace, $) { "use strict"; var AppForm = function() { // Cr ...

Tips for utilizing flexbox and React-Native to ensure a cropped image takes up the entire View

I'm trying to create a cropped image that fills the entire screen in my app. Currently, my code looks like this: https://i.stack.imgur.com/9DtAc.png However, I want the small square of Homer eating donuts to occupy the entire screen, similar to the ...

Is there a method available within the Collada loader to extract multiple meshes from the scene object?

Recently, I delved into some experimental work with Blender and the Collada Loader in three.js. Within my Blender project, I have three distinct objects, but when using the loader in three.js, I can only manipulate them as one single scene object. While ev ...

Tips on incorporating a high-quality animated gif for optimal user engagement

I'm looking for advice on how to optimize the loading of a large animated gif (1900px wide) on my website. Currently, the initial load time is quite lengthy and the animation appears choppy. Is there a more efficient method to load the gif without slo ...

Can anyone tell me the location of the modalColor with the background set to 'greenYellow' in the popup window?

Take a look at the sample in jQuery.bPopup.js called Example 2b I am trying to design a popup window with customized text and background style, using the Example 2b, custom settings: Simple jQuery popup with custom settings (Jamaican popup, relax man) $ ...

Access the style of the first script tag using document.getElementsByTagName('script')[0].style or simply refer to the style of the document body with document.body.style

Many individuals opt for: document.getElementsByTagName('script')[0].style While others prefer: document.body.style. Are there any notable differences between the two methods? EDIT: Here's an example using the first option: ...

Utilize MaxMind GeoIP2 to identify the city accurately

I have been using this simple code to retrieve the city name through the maxmind service (geoip2). It has been working flawlessly and I am grateful to a fellow member of this site who shared this code with me. However, there is an issue when the user&apos ...

Selenium's WebDriver getAttribute function can return an object of type "object",

In my selenium script, I aim to extract text from table columns following the cell with the specified value. Although the script functions, I encounter an issue where getText() returns [Object Object] in my node.js console. I have attempted various method ...

Is it possible to include more than one ng-app directive on a single HTML page in AngularJS?

When working with Angular JS, I've noticed that I only get the desired output if I remove either the ng-app directive for demo1 or the models. It seems like having two ng-app directives active at the same time causes issues. As a beginner in Angular J ...

Tips for consistently obtaining the executed value of a getter in Mongoose?

In my mongoose schema, I have implemented a getter function for one of the properties as shown below: const User = new mongoose.Schema( { active: Boolean, email: {type: String, get: toLowerCase} } ) The toLowerCase function is def ...

Avoiding an event from spreading in Angular

I am working on a navigation setup that looks like this: <a (click)="onCustomParameters()"> <app-custom-start-card></app-custom-start-card> </a> When the user clicks on the app-custom-start-card, the onCustomParame ...

An unusual html element

During a recent exploration of a website's code using the inspect tool, I stumbled upon a tag that was completely unfamiliar to me. <gblockquote></gblockquote> I've come across a blockquote before, but never a gblockquote. Interest ...

Robmongo - combine unique values based on different columns

As a newcomer to robmongo, I've been tasked with writing queries for a collection that includes keys like "userId" and "deviceModel." My goal is to create a query that shows the number of users for each device model. Here is the query I have so far: ...

The request has been unsuccessful with error code 405 in Nextjs version 14

I am currently working with NextJs version 14 and encountering a 405 error: GET http://localhost:3000/api/products 405 (Method Not Allowed) Uncaught (in promise) AxiosError products.js "use client" import { useState } from 'react'; ...

The chosen choice is not able to be shown within the option tag

When attempting to filter options using JavaScript based on a selected item, I'm encountering issues. If the selected element contains 'CONTINUE' or 'BRACKET', it should be split into an array by space and only the first two indice ...

What is the process by which Elastic Beanstalk executes Node.js application code?

While my application runs smoothly on localhost, encountering no issues, deploying it to other platforms such as AWS or MCS presents a challenge. Specifically, the problem lies in recognizing the file paths required by the consign library to load the route ...

Having trouble adding/removing/toggling an element class within a Vue directive?

A successful demonstration can be found at: https://jsfiddle.net/hxyv40ra However, when attempting to incorporate this code within a Vue directive, the button event triggers and the console indicates that the class is removed, yet there is no visual chang ...