Why there is no built-in zip function in JavaScript?

I’m just curious why there isn’t any built-in zip function in javascript.

I’ve used a number of modern or older programming languages, such as python, kotlin, and rust. These days I’m writing codes in javascript and enjoying functional programming with it, since it provides built-in higher order functions such as filter, map, and reduce. At the same time it seems that the javascript community encourages functional programming.

However, I encountered a question: Why javascript does not provide zip function?

It is provided in many other programming languages and very useful and convenient when I need to work with multiple iterables in parallel. For example, in python:

numbers = [1, 2, 3]
upper = ["A", "B", "C"]
lower = ["a", "b", "c"]

for n, u, l in zip(numbers, upper, lower):
    print(f"{n}, {u}, {l}")

Of course the same result can be achieved in javascript, using map or forEach, or for loop.

const numbers = [1, 2, 3];
const upper = ["A", "B", "C"];
const lower = ["a", "b", "c"];

numbers.forEach((n, i) => {
    console.log(`${n}, ${upper[i]}, ${lower[i]}`);
});

It doesn’t look so neat for me, so I may write a custom zip function.
(btw, it won’t work correctly when iterables of different sizes are provided.)

function zip(...iterables) {
    return iterables[0].map((_, i) => iterables.map((it) => it[i]));
}

zip(numbers, upper, lower).forEach(([n, u, l]) => {
    console.log(`${n}, ${u}, ${l}`);
})

But I don’t want to write this everytime.
Neither to add any library for it.

So what’s the reason there’s no built-in one?

Javascript json customization

Hi here i am trying to manipulate one json file to below format. I am not able to think how to do that ?

The way i am thinking is not efficient thats why i need hep on this ?

Is there any easy way to do this.

Please have a look

[
 {
    "nid": "61629",
    "title": "K02 - Kiosk Slider - EN",
    "itemsSlider": [
      {
        "nid": "61626",
        "status": "1",
        "titleNode": "01Additional Suitcase - EN",
        "language": "en_US"
      },
      {
        "nid": "61626",
        "status": "1",
        "titleNode": "01Additional Suitcase - EN",
        "language": "en_US"
      }
    ]
  },
  {
    "nid": "61629",
    "title": "K02 - Kiosk Slider - EN",
    "itemsSlider": [
      {
        "nid": "61626",
        "status": "1",
        "titleNode": "01Additional Suitcase - EN",
        "language": "es_MX"
      },
      {
        "nid": "61626",
        "status": "1",
        "titleNode": "01Additional Suitcase - EN",
        "language": "es_MX"
      }
    ]
  },
  {
    "nid": "61629",
    "title": "K02 - Kiosk Slider - EN",
    "itemsSlider": [
      {
        "nid": "61626",
        "status": "1",
        "titleNode": "01Additional Suitcase - EN",
        "language": "fr_FR"
      },
      {
        "nid": "61626",
        "status": "1",
        "titleNode": "01Additional Suitcase - EN",
        "language": "fr_FR"
      }
    ]
  },
  {
    "nid": "61629",
    "title": "K02 - Kiosk Slider - Mix",
    "itemsSlider": [
      {
        "nid": "61626",
        "status": "1",
        "titleNode": "01Additional Suitcase - EN",
        "language": "es_MX"
      },
      {
        "nid": "61626",
        "status": "1",
        "titleNode": "01Additional Suitcase - EN",
        "language": "en_US"
      }
    ]
  }
]

THis this the output i am expecting for:
Please have a look Is there any way to achive it?

{
  "es_MX": [
    {
      "nid": "61626",
      "status": "1",
      "titleNode": "01Additional Suitcase - EN",
      "language": "es_MX"
    },
    {
      "nid": "61626",
      "status": "1",
      "titleNode": "01Additional Suitcase - EN",
      "language": "es_MX"
    }
  ],
  "fr_FR": [
    {
      "nid": "61626",
      "status": "1",
      "titleNode": "01Additional Suitcase - EN",
      "language": "fr_FR"
    },
    {
      "nid": "61626",
      "status": "1",
      "titleNode": "01Additional Suitcase - EN",
      "language": "fr_FR"
    }
  ]
}

How to check input between min & max number in react?

I have 2 costs min & max. I want when user type number in input manually then the user can only type number between min & max number. i want to do it in React/Next js.

<Input
    value={tripCoverage}
    onChange={(e) => {
        const value = e.target.value;
        const { minCost, maxCost } =
            studentPrice()?.tripCost || {};
        const result = Math.max(
            minCost,
            Math.min(maxCost, Number(value))
        );
        setTripCoverage(result);
    }}
    type="number"
/>

at the time of downloading files from s3 bucket one file is not able to download

anthi:_anti_hair_thinning_hair_spray.png
this the file name in s3 when it downloaded using s3 client it save file with name anthi and with 0kb also file type shows file , wherever in s3 it is 100kb and file type is png

I am using fs to save the file locally with same name please help me

 const objects = await s3.listObjectsV2(listParams).promise();
        for (const object of objects.Contents) {
            if (object.Size >= MIN_FILE_SIZE_IN_BYTES) {
                const fileKey = object.Key;
                const fileExtension = path.extname(fileKey).toLowerCase();
                if (allowedFileExtensions.includes(fileExtension)) {
                    const localFilePath = path.join(localDownloadFolder, path.basename(fileKey));
                    const data = await s3.getObject({ Bucket: bucketName, Key: fileKey }).promise();
                    fs.writeFileSync(localFilePath, data.Body);
                    // console.log(`File downloaded to: ${localFilePath}`);
                }
            }
        }

I will be very thankful for any suggestion or advice.

i tried to download files form asw s3 bucket

it is failing to download file name (anthi:_anti_hair_thinning_hair_spray.png ) with column

as using fs to write file in folder

how could i fix this?

Problems getting response of API request using Postman error { } [duplicate]

I created some documents in MongoDB that are Families, Users, Devices (https://i.stack.imgur.com/oeDU0.png)
What I’m trying to do is to display all devices within a specific family using the Id from http request. For example, http://localhost:8567/get?familyId=65f1dcc828d6b2d79bb2f4b4

Here is the models in VSCODE

My router:

const router = require('express').Router();
const DevicesControl = require('../Controller/DevicesController');

// GET
router.get('/get', DevicesControl.getFamilyDevices);
module.exports = router;

My controller:

const mongoose = require('mongoose');
const Devices = require('../HomeModel/Devices');
const Families = require('../HomeModel/Families');
const ObjectId = mongoose.Types.ObjectId

const DevicesControl = {

    getFamilyDevices: async (req, res) => {
        try {
            console.log('GET request is active');
            const familyId = req.query.familyId;
            if (!familyId) {
                res.status(404).json('Family not found');
            }
            const foundFamily = await Families.findById(familyId);
            const devices = await foundFamily.devices()
            res.status(200).json(devices)
;
        }
        catch (error) 
        {
           res.status(500).json({ error: 'Error getting Devices', details: error });
        }
    }
};
module.exports = DevicesControl;     

The { } error in Postman here

I tried with simply returning the familyId from the request and it worked just fine. However, when it comes to returning documents everything is different.
I’m hoping the correct response should return the devices in ‘Devices’ model (https://i.stack.imgur.com/6EaSw.png)

I looked at some resources, perhaps the error representa empty object. I’m super new to this stuff and can’t solve it myself. Please help me figure out what’s going wrong with that error and how to fix it.

Data table refresh and pagination

i’m working on a simple crud data table, i add refresh function without reloading the page using ajax to append html. it works fine, then there’s conflict when i add pagination from laravel. the table only shows the first 5 data from fetched data on the next page.

$(document).ready(function() {
  // Function to refresh table data
  function refreshTable(page) {
      $.ajax({
          url: '/get-latest-projects?page=' + page, // URL to fetch updated data
          method: 'GET',
          success: function(response) {
              // Update table with new data
              $('#dataTable tbody').html(' '); // Assuming data is HTML for the table body only

              $.each(response.data, function(index, item) {
                var row = '<tr class="tr">';
                row += '<td>' + item.input_date + '</td>';
                row += '<td>' + item.nama_project + '</td>';
                row += '<td class="desc">' + item.requestor + '</td>';
                row += '<td>' + item.category_project + '</td>';
                row += '<td><span>' + item.description_project + '</span></td>';
                row += '<td>' + item.status + '</td>';
                row += '<td><span class="status--process">' + item.pic_project + '</span></td>';
                row += '<td>' + item.eta_project + '</td>';
                row += '<td><div class="table-data-feature" id="editContainer">';
                row += '<button type="button" class="item" data-toggle="modal" data-target="#editModal' + item.id + '" data-placement="top" title="Edit"><i class="zmdi zmdi-edit"></i></button>';
                row += '<button class="item" data-toggle="tooltip" data-placement="top" title="Delete"><i class="zmdi zmdi-delete"></i></button>';
                row += '</div></td></tr>';
                $('#dataTable tbody').append(row);
            });
          },
          error: function(xhr, status, error) {
              console.error('Error refreshing table:', error);
          }
      });
  }

  refreshTable(1);

  // Reload table when the button is clicked
  $('#reloadButton').click(function() {
      refreshTable(1);
  });
});

the table is able to show the next data on next page only for a blink then covered by appended html which containing new data fetched

    public function index()
    {
        $projects = Project::orderBy('id', 'desc')->paginate(5);
        return view('table', compact('projects'));

    }


    
    public function getLatestProjects()
    {
        $projects = Project::orderBy('id', 'desc')->latest()->paginate(5); // Adjust as needed
        return response()->json($projects);
    }

this is another try from before which the object wasn’t defined.

How to use signalr invoke a function from server side to cancel the upload progress?

Signalr backend controller setup:

namespace Antz.App.SignalR.Hubs
{
    public class ProgressHub : Hub
    {
        public static bool IsCancelled = false;

        public void SendProgress(string progressMessage, int progressCount, int totalItems)
        {
            //Thread.Sleep(1);
            var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();
            var percentage = (progressCount * 100) / totalItems;
            hubContext.Clients.All.AddProgress(progressMessage, percentage + "%");
        }

        public void IsCancelledUpload()
        {
            IsCancelled = true;
        }
    }
}

Javscript:

signalrConnection = $.hubConnection("/SignalR", { useDefaultPath: false });
signalrProxy = signalrConnection.createHubProxy('ProgressHub');

signalrProxy.on('AddProgress', function (message, percentage) {

    UpdateProgressBar(percentage);

});

/* signalrConnection.logging = true;*/

signalrConnection.start({ transport: 'longPolling' }).then(function () {

    console.log("Connection Started");

});

signalrConnection.disconnected(function () {
    console.log('Disconnected');

    setTimeout(function () {
        signalrConnection.start({ transport: 'longPolling' }).then(function () {
            console.log("Connection Started");
        });
    }, 3000);
});

signalrConnection.error(function (error) {
    console.log(error);
});

function UpdateProgressBar(percentage) {

    const progressBar = document.querySelector(".progress-bar");
    progressBar.style.opacity = "1";
    progressBar.style.width = percentage;
    progressBar.innerHTML = percentage;

    if (percentage === "100%") {

        progressBar.style.width = "";
        progressBar.innerHTML = "";

    }
}

Upload function backend controller:

ProgressHub progressHub = new ProgressHub();

var refNoList = new List<string>();
await Task.Run(async () =>
{
    foreach (ArrayList row in data3)
    {
        recordProcessed++;

        rowIndex++;
        // skip row 1 as it's a header
        if (rowIndex == 1)
        {
            continue;
        }

        progressHub.SendProgress("Process in progress...", rowIndex, totalRows);
        //await Task.Delay(5000); // Introduce a small delay

        bool all_pass = true;

        string docType = row[0].ToString().Trim();
        string refNo = row[1].ToString().Trim();
        string vendor = row[2].ToString().Trim();
        string remark = row[3].ToString().Trim();

I’ve tried to put a static field on the class ProgressHub and if the user was clicked the cancel button, the button will trigger the signalr to invoke the function IsCancelledUpload which is use to update the IsCancelled boolean to true. So Excel upload function will check if the boolean is true, the loop will be break. But using static is not a wise choice, so I’m seeking another approach for this.

how seTimeout() executing continuously?

Since we know that setTimeout() function execute only once then how the following program executing continuously:

import {useState} from "react"

const App = () => {

        const [counter, setcounter] = useState(0);

        setTimeout( () => setcounter (counter+1), 1000)
        

        return (
          <div>{counter} </div>
        )

}

export default App

please anybody can identify it? which code piece triggering the setTimeout() to execute continuously?

how to use buttons with the onClick method in the latest nextJS version 14.1.3

"use client"
import React, { useState } from "react";
import { FaChevronLeft, FaChevronRight } from "react-icons/fa";

export default function HeroSlider() {
  const images = [
    "/images/homepage/home-1.jpeg",
    "/images/homepage/home-2.jpg",
    "/images/homepage/home-3.jpg",
    "/images/homepage/home-4.jpg",
    "/images/homepage/home-5.jpg",
    "/images/homepage/home-6.jpg",
    "/images/homepage/home-7.jpg",
  ];
  const [currentImageIndex, setCurrentImageIndex] = useState(0);

  const nextImage = () => {
    setCurrentImageIndex((nextIndex) =>
    nextIndex === images.length - 1 ? 0 : nextIndex + 1
    );
  };

  const prevImage = () => {
    setCurrentImageIndex((prevIndex) =>
      prevIndex === 0 ? images.length - 1 : prevIndex - 1
    );
  };

  return (
    <div>
      <div style={{ position: "relative", width: "100%", height: "auto" }}>
        <img
          src={images[currentImageIndex]}
          alt="Your Image"
          style={{ width: "100%", height: "auto", objectFit: "cover" }}
        />
        <div
          style={{
            width: "5%",
            position: "absolute",
            top: "50%",
            left: "0",
            transform: "translateY(-50%)",
            zIndex: 1,
          }}
        >
          <button
            type="button"
            onClick={prevImage}
            className="absolute top-1/2 left-0 transform -translate-y-1/2 bg-transparent border-none"
          >
            <FaChevronLeft size={40} color="white" />
          </button>
        </div>
        <div
          style={{
            width: "5%",
            position: "absolute",
            top: "50%",
            right: "0",
            transform: "translateY(-50%)",
            zIndex: 1,
          }}
        >
          <button
            type="button"
            onClick={nextImage}
            className="absolute top-1/2 right-0 transform -translate-y-1/2 bg-transparent border-none"
          >
            <FaChevronRight size={40} color="white" />
          </button>
        </div>
      </div>
    </div>
  );
}

why do the nextImage and prevImage functions not work?

I’m making a slider hero component, so I applied the use state concept, and created the nextImage and prevImage functions to change the useState value via the button with the onClick method, but why isn’t that function called? Can anyone help me here?

I can’t perform most operations over npm, like downloading packages

I want to learn backend using node.js on my computer but the npm command is not working. When I say it’s not working, I mean I want to install a file and it doesn’t give any errors but I can’t use the packages.

npm i cors

up to date, audited 852 packages in 6s

found 0 vulnerabilities

Also it’s packet.json

{
  "name": "deneme",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "*",
    "express": "*",
    "nodemon": "*"
  }
}

It doesn’t show in the versions after installation

const express = require('express')

const app = express()

app.listen(4000 , () => {
    console.log('hello');
})
node deneme.js
node:internal/modules/cjs/loader:1145
  throw err;
  ^

Error: Cannot find module 'express'
Require stack:
- C:*******Desktopdenemedeneme.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1142:15)
    at Module._load (node:internal/modules/cjs/loader:983:27)
    at Module.require (node:internal/modules/cjs/loader:1230:19)
    at require (node:internal/modules/helpers:179:18)
    at Object.<anonymous> (C:*******Desktopdenemedeneme.js:1:17)
    at Module._compile (node:internal/modules/cjs/loader:1368:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1426:10)
    at Module.load (node:internal/modules/cjs/loader:1205:32)
    at Module._load (node:internal/modules/cjs/loader:1021:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:142:12) {
  code: 'MODULE_NOT_FOUND',

Tried Solutions:
-Tried different npm versions.
-Checked the PATH variable.
-Ran commands as administrator.
-Cleared the npm cache (I cant because its not working )

Does anyone know the reason for the issue and how to fix it?

I tried to download ‘npm i cors’ and other packages, but it didn’t work. Something is blocking it, but I couldn’t solve it. I already provided the details above

vite + Vue.js 3: how to build with the final export value?

I have a large ts data file:

data.ts :

export data = [
  ... // huge data 
]

the lib.ts just use some of the data:

import { data } from './data.ts';

const fitteredData = data.splice(0,2) // only use some of them

export { fitteredData };

I use fitteredData in my vue component:

<script setup lang="ts">
import { fitteredData } from "./lib";
</script>

<template>
  <div>{{ fitteredData }}</div>
</template>

After run pnpm build, I find all of the data in data.ts are builded in final file. How to make the final file only with the fitteredData?

How to make the final file only with the fitteredData, to make the final builded files smaller.

Using bycrpt.compare in node.js app but it isn’t being called or working at all

I am using bycrypt for my login process and it doesn’t seem to be working. I have already stored the previously hashed password in the database so I am retrieving it from the database and then comparing it with the password but it is like my bycrpt.compare isn’t even being activated in my code. I have verified that my password and the hashed password are there, and they do work but still nothing.

Here is my code:

app.post("/login", (req, res) => {
  const username = req.body.username;
  const password = req.body.password;

  const responseArr = [];
  let passwordStatus = "";

  db.query(
    "SELECT password FROM users WHERE username = $1",
    [username])
    .then((res) =>  {
      
        const hash = res.rows[0].password;
        console.log("hash", hash);
        console.log("password", password);



        bcrypt.compare(hash, password, function(err, result) {
          console.log("in func", res.rows[0].password)
          console.log("in func", password)
        
              if(result){
                  console.log("login success");
                  console.log(result);

                  passwordStatus = true;
                  

              }else{
                  console.log('login failed');
                  passwordStatus = false;
              }

              if (err) {
                console.log("err", err)
              }
          })
   
        console.log("passwordStatus", passwordStatus);
        return passwordStatus;
      })
    .then((result) => {
      if (result === true) {
        const userResponse = db.query(
          "SELECT user_id FROM users WHERE username = $1;",
          [username]
        );
        return userResponse;
      } else {
        res.status(404);
        console.log("result was false")
      }
    })
    .then((response) => {
      responseArr.push(response.rows);
      res.status(200).send(responseArr);
    })
    .catch((error) => {
      console.log("error:", error);
      if (error) {
        throw error;
      }
    });
});```

Tab key is always hiding the Datepicker (accessibility)

<input id="BirthDate.0" name="BirthDate.0" class="input-sm input_mask mask_date form-control hasDatepicker" onchange="updateFieldGrid('UpdateField', this)" style="" value="" type="text" aria-label="Birth Date" size="11" maxlength="10" placeholder="mm/dd/yyyy" autocomplete="off">

$('input[type="text"].hasDatepicker').keydown(function(event) {
    var target = $(event.target);
    if(event.keyCode == 9) {
        if(!target.datepicker("widget").is(":visible")) {
            target.datepicker("show");
        } else {
            target.datepicker("hide");
        }
    }
});

I have been asked to make a datepicker more accessible, IE a user navigates to the birth date field using the tab key, hits the tab key again, the datepicker opens and they are able to navigate the picker via keyboard buttons, they hit tab again and it closes the picker and focus shifts to the next form element.

The above code gets the datepicker to show when hitting the ‘tab’ key. However, if you hit tab twice to hide it from the same focused text input field target.datepicker("widget").is(":visible") still evaluates to false. It in fact always evaluates to false. If I check for a different keypress, say the ‘a’ key which has a keycode of 65 it will indeed hide the datepicker on the second keypress. I’ve tried event.preventDefault() but this still doesn’t resolve it.

For the life of me I am unable to debug why this is happening and why it is always hiding the datepicker whenever I press ‘tab’ and before the keydown event handler is activated. The debugger shows it being already closed when it enters the keypress handler despite it having been opened when I pressed the key, and this isn’t happening for most other keys. So my guess is somewhere upstream prior to the keydown handler being called it is hiding the datepicker, but where?

Edit:
I found the following snippet in the jquery-ui-1.13.2.min.js file:

    _doKeyDown: function(a) {
        var b, c = d.datepicker._getInst(a.target);
        b = !0;
        var f = c.dpDiv.is(".ui-datepicker-rtl");
        c._keyEvent = !0;
        if (d.datepicker._datepickerShowing)
            switch (a.keyCode) {
            case 9:
                d.datepicker._hideDatepicker();
                b = !1;
                break;

I set the breakpoint to the datepicker being hidden basically, and it is executing this code. It looks to be default datepicker functionality to hide the datepicker on tab keypress (keycode = 9). Any way to override this?