How to convert a date string into month day year time

I would like to convert this date string “2023-11-10T11:00:00” into two variables, one containing the date and one containing the day and time. Something like this:

const date = "Nov 10, 2023";
const time = "Saturday 11:00 AM";

How could I write a function to do this? Thank you so much in advance!

Properties on base class are not defined on properties on sub class

I have one class extending another class and a function that runs on the base class is setting properties but the sub class properties are all null. In the debugger the base class has all all property values.

Is there something I’m missing?

class Fruit {
    count = 0;
    pick() {
       this.count = 10;
    }
}

class Apple extends Fruit {
    constructor() { super() }
}

window.addEventListener("DOMContentLoaded", (event) => {
  var apple = new Apple();
  apple.pick();
  console.log(apple.count); // 0
})

My code is something like above but it works here. My classes are modules and run as modules. I’m using Typescript as well.

why do checkbox events give panic: ValueOf: invalid value

I have a very normal golang wasm setup. A wasm_exec.js from go 1.21.0 and everything is working great. I can call:

button.Set("onclick", js.FuncOf(MyClick))

and lots of other stuff. But then I tried:

box.Set("onchange", js.FuncOf(CheckChange))

and everytime I get:

panic: ValueOf: invalid value

syscall/js.ValueOf({0x3d540, 0xeffe8}) wasm_exec.js:22:14
    /usr/local/go/src/syscall/js/js.go:209 +0xf6 wasm_exec.js:22:14
syscall/js.Value.Set({{}, 0x7ff800010000014a, 0x180d8b0}, {0xa3cfd, 0x6}, {0x3d540, 0xeffe8}) wasm_exec.js:22:14
    /usr/local/go/src/syscall/js/js.go:306 +0x8 wasm_exec.js:22:14
syscall/js.handleEvent() wasm_exec.js:22:14
    /usr/local/go/src/syscall/js/func.go:103 +0x26

If you look at the go source:

  cb := jsGo.Get("_pendingEvent")
  cb.Set("result", result)

the cb.Set line is throwing the panic. Why only for onchange checkbox events?

ES6; Nested Promise.all (Maybe?)

The post title may not be entirely accurate as I’m not even sure if my approach to this is the best way. I’ll let the community decide.

Working with Javascript(ES6), in a React app.
Example Data (Original):

dataArray = 
[
{"uid": 3, "region": "bru", "hostname": "bru-002.domain.com", "status": "active"}, 
{"uid": 1, "region": "bru", "hostname": "bru-001.domain.com", "status": "disabled"},
{"uid": 4, "region": "apc", "hostname": "apc-001.domain.com", "status": "active"}
];
  • The object key names with-in each array are static. We can assume if there is an object, it will contain the key name ‘hostname’, etc.
  • Live data will have hundreds of entries for each region and dozens of other object fields (keys). Not really relevant for the code, just FYI.

The end goal is to perform a HTTP request for each host and collect the results from the request. That functionality is already written and in use.
The brain-breaker I’ve run into is a CR to separate these calls into ‘blocks by region’. In other words, perform all calls for first region and when that is done, THEN initiate calls for next region, etc. The final results of all calls will go into a setState().

The existing code uses Promise instead of async/await. Most of the time I use await, but in some cases I do like the clear code readability that a Promise in conjuction with a .then provides.

This is a snippet of current in-use code. It’s in an useEffect block.:

...
Promise.all(
  dataArray.map(function(host) {
    if (host['status'] !== 'disabled') {
      return pinger(host.hostname);
    }
    return ''; // Default return to satisfy map function
  }))
  .then(result => {
    setPingedData(result); // Using a React set State
  }
);
...

The above code works, but en masse. To separate it out, I started by creating a new object that ends up looking like this:

sortedByRegionObj = 
{ "bru": [{"uid": 3, "hostname": "bru-002.domain.com", "status": "active"}, 
          {"uid": 1, "hostname": "bru-001.domain.com", "status": "disabled"}],
  "apc": [{"uid": 4, "hostname": "apc-001.domain.com", "status": "active"}]
};
  • The top level object key names represent ‘region groups’.
  • The region names will be dynamic. We can only assume if there is a region, the value of that region will be an array of 1 or more objects.
  • The arrays represent how we want to group the HTTP calls. The array would be one group of Promises.

And the idea was to walk through the object using something like:

for (const regionArray of Object.values(sortedByRegionObj)) {
 Promise.all(
          regionArray.map(function(host) {
...

(The above code is not valid- just depicting the general idea)

and create Promise arrays and then use Promise.all… but then I got lost. The part that stumped me was having a dynamic number of objects when trying to create an array for Promise.all…
I can’t wrap my head around how to do this.

Thoughts?

Context API is returning undefined react

I have a source component in which I am trying to use context api. Below is my code of SourceComponent.js. I am trying to fetch the fileType data using the concept of context Api using useContext

    import React, {useContext} from "react";
    import { MappingData } from "./DataProviders/MappingDataProvider";
    import { Select } from '@appkit/react-components'

    const SourceComponent = () => {
        const CreateMappingData = useContext(MappingData);
        return (
          
            <>
            {console.log('CreateMappingData',CreateMappingData)} // Here the CreateMappingData is undefined in console
                <div>Source</div>
                <div className="form-group">
                <Select
                  data={CreateMappingData.fileType}
                  searchable={true}
                  name="FileType"
                  required={true}
                  placeholder={"File Type"}
                  valueKey={"File Type"}
                  labelKey={"File Type"}
                ></Select>
                </div>
                
            </>
        )
    }

    export default SourceComponent;

And then the code of MappingDataProvider.js is below

    import React, {useEffect, useState, createContext} from "react";

    export const MappingData = createContext();

    export const MappingDataProvider = ({children})=>{
        const [fileType, setFileType] = useState([]);
        
        useEffect(()=> {
            fetchFileType();
        }, [])


        const fetchFileType = () => {
            setFileType([
            { value: 'client', label: 'Client' },
            { value: 'project', label: 'Project' },
            { value: 'user', label: 'User' },
            
        ])
    };
        
        return(
            <MappingData.Provider
            value={
                {fileType}
            }
            >
                {children}
            </MappingData.Provider>
        )
    }

Here I am getting CreateMappingData as undefined and also Cannot read properties of undefined (reading 'fileType')

Where did I go wrong?

Quick sort implementation JavaScript

Im trying to implement quick sort. I wrote partition function which returns array, where first element – number of elements less than pivot and the second – the amount of rest elements.

I ran some tests but i keep getting unlimited recursion. Somehow the array changes only one time and that is it.

I was trying for over a week now 🙁

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

let c, arrSize;
let flagE = false;
let flagG = false;
let flagN = false;

function partition(arr, l, r, pivot){
  let E, G, pointerE, pointerG;
  let N = arr[l];
  while (l <= r){
    if (N > pivot & !flagG){
      G = N;
      pointerG = l;
      flagG = true;
    } else if (N === pivot & !flagE){
      E = N;
      pointerE = l;
      flagE = true;
      if (flagG) {
        arr[l] = G;
        arr[pointerG] = N;
        pointerE = pointerG;
        pointerG++;
      }
    }
     else if (N < pivot & !E & !G){
      flagN = true;
    } 
    else if (N > pivot & flagG) {
      N = arr[l];
    } else if (N < pivot) {
        if (E & G) {
            arr[l] = G;
            arr[pointerG] = E;
            arr[pointerE] = N;
            pointerG++;
            pointerE++;
        } else if (G){
            arr[l] = G;
            arr[pointerG] = N;
            pointerG++;
        } else if (E){
            arr[l] = E;
            arr[pointerE] = N;
            pointerE++;
        }
    }
    l++;
    N = arr[l];
    G = arr[pointerG];
    E = arr[pointerE];
  }

  if (!pointerE & !pointerG & !flagN) {
      return([0, arrSize]);
  } else if (!pointerE & !pointerG & flagN){
      return([arrSize - 1, 0]);
  } else if (pointerE){
      return ([pointerE, r - pointerE]);
  } else if (pointerG & !pointerE) {
      return ([pointerG, arrSize - pointerG]);
  } else {
      return ([pointerG, arrSize - pointerG]);
  }
}

function quickSort(arr, l, r) {
  if (l < r) {
    let x = Math.floor((l + r) / 2);
    let [p, j] = partition(arr, l, r, arr[x]);
    quickSort(arr, l, p);
    quickSort(arr, p + 1, r);
  }
}


readline.on('line', input => {
  let arr;
  if (!c) {
    arrSize = Number(input);
    c = 1;
  } else if (c === 1){
    arr = input.split(' ').map(Number);
    c++;
  }
  if (c === 2){
    quickSort(arr, 0, arrSize - 1);
    console.log(arr.join(' '));
    readline.close()
  }
})

partition algorithm using 3 pointers

How to attach toString to proxy handler

Consider this code:

handler.toString = function() {
    return Reflect.get(original,'toString');
}
    handler.apply = scope.exportFunctionWithName(function(target, thisArgs, args){
        try {
            return args.length?
                replacement.call(thisArgs, ...args):
                replacement.call(thisArgs);
        }
        catch (error){
            try {
                return original.apply(thisArgs, args);
            }
            catch (error){
                return target.apply(thisArgs, args);
            }
        }
    }, window, "");
    const proxy = new window.Proxy(original, handler);

if I invoke ApiObj.toString(), it works as expected.

Now if I want to invoke ApiObj.toString.caller, it errors out, with

get caller method called on incompatible proxy

How can I fix this ?

Getting Error fetching student data: SyntaxError: Unexpected token ‘<', "<!DOCTYPE "… is not valid JSON error

I am new to react and am creating a simple laundry management system. I have written the front end code using React. The full App.js code is below:

import React, { useState, useEffect } from 'react';

function AdminInterface() 
{
  const [registrationNumber, setRegistrationNumber] = useState('');
  const [studentData, setStudentData] = useState(null);

  // Function to fetch student data by registration number from the backend
  const fetchStudentData = async () => {
    try 
    {
      const response = await fetch(`http://localhost:4000/students?student_id=${registrationNumber}`);

      if (!response.ok) 
      {
        // Handle HTTP errors
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
    
      const data = await response.json();
      setStudentData(data); // Set the studentData state with the fetched data
    } 
    catch (error) 
    {
      // Handle network issues or other errors
      console.error('Error fetching student data:', error);
      throw error;
    }
  };

  useEffect(() => {
    // Fetch student data when the component mounts
    if (registrationNumber) 
    {
      fetchStudentData();
    }
  }, [registrationNumber]);

  return (
    <div>
      <h1>Admin Interface</h1>
      <input
        type="text"
        placeholder="Enter Registration Number"
        value={registrationNumber}
        onChange={(e) => setRegistrationNumber(e.target.value)}
      />
      <button onClick={fetchStudentData}>Get Student Data</button>

      {studentData && (
        <div>
          {/* Display student data here */}
          <p>Name: {studentData.name}</p>
          <p>Student ID: {studentData.student_id}</p>
          <p>Washes Remaining: {studentData.number_of_washes_remaining}</p>
        </div>
      )}
    </div>
  );
}

export default AdminInterface;

I have also written the back end for this using express and MongoDB. The server.js code is given below:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');

const app = express();

// MongoDB Connection
mongoose.connect('mongodb://localhost/laundryDB', { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => console.log('Connected to MongoDB'));

// Middleware
app.use(bodyParser.json());
app.use(cors());

// Define the schema for the Students collection
const studentSchema = new mongoose.Schema({
  name: String,
  student_id: String,
  number_of_washes_remaining: Number,
});

// Create the model for the Students collection
const Student = mongoose.model('Student', studentSchema);

// Define the schema for the Laundry bags collection
const laundryBagSchema = new mongoose.Schema({
  student_id: String,
  number_of_washes: Number,
  time_submitted: Date,
});

// Create the model for the Laundry bags collection
const LaundryBag = mongoose.model('LaundryBag', laundryBagSchema);

// Define the schema for the QR codes collection
const qrCodeSchema = new mongoose.Schema({
  student_id: String,
  qr_code: String,
});

// Create the model for the QR codes collection
const QRCode = mongoose.model('QRCode', qrCodeSchema);


app.post('/students', async (req, res) => {
  try 
  {
    // Implement student registration logic
    const { name, student_id } = req.body;
    const newStudent = new Student({ name, student_id, number_of_washes_remaining: 4 });
    const savedStudent = await newStudent.save();
    res.status(201).json(savedStudent);
  } 
  catch (error) 
  {
    res.status(500).json({ error: 'Unable to register student' });
  }
});

app.put('/laundrybags/:id', async (req, res) => {
  try 
  {
    // Implement laundry bag update logic
    const laundryBagId = req.params.id;
    const { status } = req.body; // 'completed', 'in progress', or 'waiting'

    // Find and update the laundry bag with the specified ID
    const updatedLaundryBag = await LaundryBag.findByIdAndUpdate(
      laundryBagId,
      { status },
      { new: true } // Return the updated document
    );

    if (!updatedLaundryBag) 
    {
      res.status(404).json({ error: 'Laundry bag not found' });
    } 
    else 
    {
      res.json(updatedLaundryBag);
    }
  } 
  catch (error) 
  {
    res.status(500).json({ error: 'Unable to update laundry bag' });
  }
});

app.put('/students/:id', async (req, res) => {
  try 
  {
    // Implement wash count modification logic
    const studentId = req.params.id;
    const { washesRemaining } = req.body;

    // Find and update the student's wash count
    const updatedStudent = await Student.findByIdAndUpdate(
      studentId,
      { number_of_washes_remaining: washesRemaining },
      { new: true } // Return the updated document
    );

    if (!updatedStudent) 
    {
      res.status(404).json({ error: 'Student not found' });
    } 
    else 
    {
      res.json(updatedStudent);
    }
  } 
  catch (error) 
  {
    res.status(500).json({ error: 'Unable to modify wash count' });
  }
});

app.get('/students/:id/bill', async (req, res) => {
  try 
  {
    // Implement bill calculation logic
    const studentId = req.params.id;

    // Find the student by ID
    const student = await Student.findById(studentId);

    if (!student) 
    {
      res.status(404).json({ error: 'Student not found' });
      return;
    }

    // Calculate the bill based on the number of washes
    const bill = calculateBill(student.number_of_washes_remaining);

    res.json({ bill });
  } 
  catch (error) 
  {
    res.status(500).json({ error: 'Unable to calculate the bill' });
  }
});

function calculateBill(washesRemaining) 
{
  return washesRemaining * 5;
}

// Start the server
const port = process.env.PORT || 4000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

The entire thing is running on localhost. The node server is running on port 4000 while the front end is running on port 3000.The mongoDB server is also up and running. These are the success messages for each of them:

server.js:

(node:64191) [MONGODB DRIVER] Warning: useNewUrlParser is a deprecated option: useNewUrlParser has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version
(Use `node --trace-warnings ...` to show where the warning was created)
(node:64191) [MONGODB DRIVER] Warning: useUnifiedTopology is a deprecated option: useUnifiedTopology has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version
Server is running on port 4000
Connected to MongoDB

App.js:

Compiled with warnings.

[eslint] 
src/App.js
  Line 37:6:  React Hook useEffect has a missing dependency: 'fetchStudentData'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

WARNING in [eslint] 
src/App.js
  Line 37:6:  React Hook useEffect has a missing dependency: 'fetchStudentData'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

webpack compiled with 1 warning

When I try to change the port to 4000 in the below line from App.js, I get the error below the code.

const response = await fetch(`http://localhost:4000/students?student_id=${registrationNumber}`);

The error:

Uncaught runtime errors:
×
ERROR
HTTP error! Status: 404
    at fetchStudentData (http://localhost:3000/main.21f8a2fd0db6306edf18.hot-update.js:35:15)

However, if I change it to 3000, the application runs and I see the textbox and button. But every time I type any character at all in the text box, I get the error:

bundle.js:45 Error fetching student data: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
fetchStudentData @ bundle.js:45
await in fetchStudentData (async)
(anonymous) @ bundle.js:52
commitHookEffectListMount @ react-dom.development.js:23150
commitPassiveMountOnFiber @ react-dom.development.js:24926
commitPassiveMountEffects_complete @ react-dom.development.js:24891
commitPassiveMountEffects_begin @ react-dom.development.js:24878
commitPassiveMountEffects @ react-dom.development.js:24866
flushPassiveEffectsImpl @ react-dom.development.js:27039
flushPassiveEffects @ react-dom.development.js:26984
commitRootImpl @ react-dom.development.js:26935
commitRoot @ react-dom.development.js:26682
performSyncWorkOnRoot @ react-dom.development.js:26117
flushSyncCallbacks @ react-dom.development.js:12042
flushSync @ react-dom.development.js:26201
finishEventHandler @ react-dom.development.js:3976
batchedUpdates @ react-dom.development.js:3994
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430

Regarding the MongoDB, this is a document I added to the students collection manually:

[
  {
    _id: ObjectId("654510f7eb83799d03397996"),
    name: 'S SS',
    student_id: '20BCE7388',
    number_of_washes_remaining: 4
  }
]

Could you please let me know what the problem with my code is so that I can solve? Would be helpful if you could tell me how to solve the issue as well.

How can i make moveable my custom element in ckeditor5

I find from database related news in my project. I am trying add a founded element datas in CKEDITOR 5. I’m using laravel.

let addingContent = `
            <p></p>
                  <div class="row mx-0 related-news-box c-pointer position-relative mb-3" data-related-new-link="${link}" title="${title}" data-related-id="${news_item_related_id}" data-target-element="${container}">
                    <div class="col-3 p-0">
                      <div class="related-news-box-img-box">
                        <img class="w-100 object-fit-cover m-0" src="${img}">
                      </div>
                    </div>
                    <div class="col-9 position-relative related-news-box-bg d-flex align-items-center">
                      <div class="px-3">
                        <div class="related-news-box-text two-line-text"> ${title} </div>
                        <div class="related-news-show-content">
                          İçeriği görüntüle
                        </div>
                      </div>
                    </div>
                  </div>
              <p></p>
            `;

            news_item_related_id+=1;

            let finalCKContent = addingContent + editors[`ckeditor{{$mainlang->slug}}`].getData();
            editors[`ckeditor{{$mainlang->slug}}`].setData(finalCKContent);

other details not important, key problem is setData is not working very well because I cant move this addingContent elements. I can add element but cant move other positions. Example for moveable objects: ck-widget__selection-handle I can add this class in related-news-box but cant move because this class functions not working.

I try

editors.ckeditortr.model.change(writer => {
  const insertPosition = editors.ckeditortr.model.document.selection.getFirstPosition();
  const element = writer.createElement('div', {
    innerHTML: addingContent,
  });

  editors.ckeditortr.model.insertContent(element, insertPosition);
});

like that codes I ask my question google bard and bard give me this code but this code is not working and not seems like a make moveable my custom element.

Knowing focused element id before submit form

I want to return focus to the html element (that fires submit of my form) after ajax checkings. because always my form is submitted the last focused element is always the submit button.

How can i know the previous elemnt that had the focus (in pure JS please)?

Thanks in advance

Modal content change height transition animation

I have a modal that has different screens/content. When new content appears the modal should animate its’ height.

It seems crazy that I can’t achieve this with pure CSS. But I can’t figure out how to make this happen. I’m even ok setting a maximum height on the modal.

I have read articles like this:
https://keithjgrant.com/posts/2023/04/transitioning-to-height-auto/

Transitioning to Height Auto (Two Ways) using either flexbox or grid but can’t figure out how to use that technique for my modal. Because the technique is based on hover. Instead of content change.

HTML:

<!-- 1. The dialog container -->
<div
   class="cms-modal-container cms-alert-modal"
   id="alert-modal"
   aria-labelledby="alert-modal-header"
   aria-hidden="true"
   data-a11y-dialog="alert-modal"
>

<!-- 2. The dialog overlay -->
<div class="cms-modal" data-a11y-dialog-hide></div>

<!-- 3. The actual dialog -->
<div class="cms-modal__content cms-modal__content--alert wrapper" role="document">
    <!-- Modal Close Button -->
    <button type="button" data-a11y-dialog-hide aria-label="Close dialog" class="cms-modal__close">
        <svg focusable="false" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg" fill="currentColor" width="20" height="20" viewBox="0 0 32 32" aria-hidden="true" class="cds--modal-close__icon"><path d="M24 9.4L22.6 8 16 14.6 9.4 8 8 9.4 14.6 16 8 22.6 9.4 24 16 17.4 22.6 24 24 22.6 17.4 16 24 9.4z"></path></svg>
    </button><!-- /Modal Close Button -->

    <h1 id="alert-modal-header" class="cms-modal-heading cms-modal-heading--alert">Alert Modal Header</h1>
        
    <!-- Modal Content Here -->
    <div class="cms-modal-alert__content slide-1">
        <p>Slide 1: This is alert modal content. The content has a maximum width of 498px so it will wrap to the next line. <a href="">Inline Test Link</a></p>
      <br>
      <button type="button" class="btn-slide-2">Slide 2</button>
    </div><!-- /Slide 1 -->

$timeout function not working after a condition in if

Sorry for the dumb question I am pretty new on AngularJS still learning it so my problem here is the $timeout function, it doesn’t work after the first “window.location.href” statement and I couldn’t figure out the issue. But if I put it in else statement it works but that’s not where I want it. I want that when that first URL is executed, 5 seconds later the second URL executes.

angular.module('Route').controller('LoginController', ['$scope', 'LoginService', '$timeout',

function ($scope, LoginService, $timeout) {
    $scope.credentials = {
        Login: '',
        Password: ''

    };
 
    $scope.login = function () {
        LoginService.login($scope.credentials)
            .then(function (response) {
                console.log("Response data: ", response.data);
                if (response.data.length > 0) {
                    window.location.href = "http://localhost:8080/Views/home.html#!/employee";

                    $timeout(function () {
                        window.location.href="http://localhost:8080"; }, 5000);
        
                } else {
                    alert("Vérifier vos données s'il vous plâit");
                    $scope.credentials.Password = '';
                }
            })
            .catch(function (error) {
                console.error("Error", error);
            });        
    };
}]);

The dropdown in side-bar not working in django

i created a side-bar in my django template, the side bar is displayed, but the dropdown is not working, i checked every thing like code or environments and didn’t found any reason for this problem . here is my code:

sidebar.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Sidebar Menu for Admin Dashboard</title>
    <!--<link rel="stylesheet" href="style.css" />-->
    <!-- Fontawesome CDN Link -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" />
    <script src="static/js/sidebar.js"></script>
    <style>
      .sidenav {
        height: 100%;
        width: 200px;
        position: fixed;
        z-index: 1;
        top: 0;
        left: 0;
        background-color: #111;
        overflow-x: hidden;
        padding-top: 20px;
      }
      
      .sidenav a, .dropdown-btn {
        padding: 6px 8px 6px 16px;
        text-decoration: none;
        font-size: 20px;
        color: #818181;
        display: block;
        border: none;
        background: none;
        width:100%;
        text-align: left;
        cursor: pointer;
        outline: none;
      }
      
      .sidenav a:hover, .dropdown-btn:hover {
        color: #f1f1f1;
      }
      
      .dropdown-container {
        display: none;
        background-color: #262626;
        padding-left: 8px;
      }
      
      .fa-caret-down {
        float: right;
        padding-right: 8px;
      }
      
     </style>
  </head>
  <body>
    <div class="sidenav">
      <a href="#">Home</a>
      <button class="dropdown-btn">Dropdown
        <i class="fa fa-caret-down"></i>
      </button>
      <div class="dropdown-container">
        <a href="#">Link 1</a>
        <a href="#">Link 2</a>
        <a href="#">Link 3</a>
      </div>
      <a href="#">Contact</a>
    </div>

  <script>
    var dropdown = document.querySelector('.dropdown-container');
    var dropdownBtn = document.querySelector('.dropdown-btn');

    dropdownBtn.addEventListener('click', function() {
      dropdown.classList.toggle('show');
    });

    dropdown.addEventListener('click', function() {
     dropdown.classList.remove('show');
    });
  </script>

    
  </body>
</html>

i tried another code but it always the same problem , please i need help

Optimizing javascript solution to “find pairs of numbers in an array and check if they are divisible by k”

I’m working on a codesignal practice problem

You are given an array of integers a and an integer k. Your task is to calculate the number of ways to pick two different indices i < j, such that a[i] + a[j] is divisible by k.

Guaranteed constraints:

1 ≤ a.length ≤ 10^5,

1 ≤ a[i] ≤ 10^9.

Now, the problem is super easy to brute force, but I’m hitting the 4s execution time limit on the later test cases. How can I optimize my solution so I can pass the later test cases?

function solution(a, k) {
    let count = 0
    
    for (let i = 0; i < a.length - 1; i++) {
        for (let e = i + 1; e < a.length; e++) {
            if ((a[i] + a[e]) % k === 0) count = count + 1
        }
    }

    return count
}