sorting through objects in arrays, adding if none exist, else replace existing

I have time slots like 9:00, 9:10, 9:20, etc. What I am trying to achieve is that when the person edits the task of that slot and clicks the button, then the task{} object is built with the timeDeclared and the info. then the task{} is added into an array if the array does not contain the timeDeclared already, if it does, it gets replaced by the new info. The goal of this is for me to then save the array into the memory that way when the page loads I can load the array from memory and place the tasks in the time slots they belong.

current outcome = it keeps getting replaced

wanted outcome = checks for existing time slot object in the array, add if it does not exist, replace if it does

$("li").on("click", "button", function () {
    let wrap = $(this).parents("li");
    let info = $(wrap).find("p").text().trim();
    let timeDeclared = $(wrap).find(".slotMinutes").text().trim();
    var task = {};
    task.time = timeDeclared;
    task.info = info;
    var tasks = [];
    add(tasks, timeDeclared)

    function add(tasks, time) {
        const found = tasks.some(el => el.time === timeDeclared);
        if (!found) tasks.push({ task });
        return tasks;
    }

    console.log(add(tasks));

    tasks.push(task)
    localStorage.setItem("data", JSON.stringify(tasks))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

JavaScript, get all relative paths [closed]

Example, I have a link https://example.com/index.html.

I want to get all the relative paths. Like these:

https://example.com/path/image.png
https://example.com/path/folder/users.json
https://test.example.com/src/hello.txt

Is it possible? like location.relativePaths?

jQuery – Includes front-end JavaScript libraries with known security vulnerabilities

I did an optimization analysis of my website with Google Lighthouse and one of the “Best Practices” issues is as follows:

Some third-party scripts may contain known security vulnerabilities that are easily identified and exploited by attackers.

And the analysis helps you with this documentation.

The problem is with the jQuery [email protected] library, I don’t actually use it but that project has Bootstrap 4 so i need the library, migrating to Bootstrap 5 is very complicated at the moment.

I import JQuery from app.js like this:

import 'jquery';
import $ from 'jquery';
window.$ = window.jQuery = $;
import 'jquery-ui/ui/widgets/datepicker.js';

The version installed with npm from the package.json is as follows:

"dependencies": {
    "jquery": "^3.5.1",
    "jquery-ui": "^1.12.1"
}

What I can do? Maybe try some different JQuery version, but I’m not sure which one is compatible with my project.

Javascript regex to solve fill in the words

I’m looking for a way to solve hangman puzzles automatically.

Let’s say my input is ___o_ and I have a word bank of “llaory” just to make it easy.

I’ll look through a big list of all english words and use a regex to search for anything that matches.

What I have so far that works is this.

import raw from "./static/wordlist.txt";
let reg = new RegExp(
 "\b" +
    letters.replace(
      /_/g,
      `[${bank}]`
    ) +
    "\b",

  "g"
);
fetch(raw)
  .then((r) => r.text())
  .then((text) => {
    if (text.match(reg)) {
      console.log(text.match(reg));
    }
  });

Bank is the word bank so in this case it is llaory.

The results from this are 2 words [‘alloy’, ‘alloo’].

The correct and only option should be alloy but alloo is an option because the code can’t recognize that only 1 o can be used.

How can I make it so that the regex knows that letters can only be used as much as there are in the bank?

I’ve seen this post Regex with limited use of specific characters (like a scrabble bank of letters) but it doesn’t seem to work when there is a letter already present as shown with the ___o_

Activate function every >javascript | django [duplicate]

I’m not a JS expert, and i’m facing some struggles to activate a function on every table row in a django aplication.

I would like that, in every time that i click on the item_total it calculates the inputed value from the item_value * item_qt, but when i try it out, it only work for the first row

That’s my table:

<tbody>
    {% for item in contract_items %}
        <tr>
            <td>{{ item }}</td>
            <td><input type="number" style="width: 90px;" placeholder="Item value" id="item_value"></td>
            <td><input type="number" style="width: 90px;" placeholder="Item qt" id="item_qt"></td>
            <td><input type="number" style="width: 90px;" placeholder="Item total" id="item_total" onclick="calculateForm();"></td>
        </tr>
    {% endfor %}
</tbody>

And that’s my script:

var calculateForm = function () {
    document.getElementById("item_total").value =
    (
        Number(document.getElementById("item_value").value) *
        Number(document.getElementById("item_qt").value)
    )
};

Turning nested rxjs concatMap to aysnc-await?

I always encounter nested concatMap, the latter http requests base on the former results.
See below example, I need get formConfig and then use the formConfig id to get application record, then xxx. Is it more readable and maintainable turning nested rxjs concatMap to aysnc await (Avoid callback hell)? Pros and cons? which one is easier to process error handling?

General nested concatMap

  ngOnInit(){
     this.http.get(`/app-config/${this.appType}`)
     .pipe(
         concatMap(formConfig => {
             this.formConfig = formConfig;
             return this.http.get(`/appl/${this.formConfig.id}`);
         }),
         concatMap(applRec => {
             this.applRec = applRec;
             return this.http.get(`/xxx/${this.applRec.recNo}`)          
         })
        tap((val) => {this.xxx = val})
         ....
     ).subscribe();
  }

Turn to async await toPromise

 constructor(){
   this.init().then();
 }
 async init() {
    this.formConfig = await this.http.get(`/app-config/${this.appType}`).toPromise();
    this.applRec = await this.http.get(`/appl/${this.formConfig.id}`).toPromise();
    this.xxx = await this.http.get(`/xxx/${this.applRec.recNo}`).toPromise();
  }

File path for Uploaded Folder is not showing

Currently, I’m facing a problem that file path for uploaded folder in not showing in Microsoft Edge after migration from IE11. In IE11, when I choose the file to upload, it shows the folder’s path and folder’s name (example: R:example.csv). But in Edge it just showing the folder’s name(example.csv). Problem with full codes. I’ve asked here with the full code. problem is, path is not showing so the alert from JavaScript is showing continuously when I try to submit.

Web Development – Screen Reader Blocks Keyboard Events

We hired an accessibility company (A360) to evaluate our web pages. Our page has a group of buttons that can be clicked only one at a time, and among their requests are:

  1. Prevent the Enter Key to click a button, instead, make Space Key do the click.
  2. Make the Right Arrow key do the same as Tab Key (move to the next button).
    Nothing extraordinary there. Just use javascript to intercept the KeyDown event, determine which type is pressed (Enter. Space, Right-Arrow), and do the appropriate action.
    I got that working like a charm….Until I turned on the Screen Reader (NVDA) 🙁
    Then everything fell apart. NVDA blocks and overrides all the KeyDown events for all the keys except the Tab.
    Anyone has idea on how to achieve what A360 is asking for with the Screen Reader turned on?

Javascript file download / blob crreation

I’ve a Vue.JS frontend and a dotnet core API. I’m trying to download a file from the API (the source of the file is irrelevant, but I’m constructing the response as follows:

[HttpGet]
[Route("[action]/{attachmentId:int}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> DownloadAttachment(int attachmentId)
{
    try
    {
        var file = await _attachmenntService.DownloadAttachment(attachmentId);
        return File(file.FileContent, file.FileType, file.FileName);
    }
    catch (Exception e)
    {
        _logger.logError(e, "DownloadAttachment: attachmentId:{@attachmentId}", attachmentId);
        return StatusCode(StatusCodes.Status500InternalServerError);
    }
}

Accessing this endpoint in postman give’s me the expected response:

enter image description here
enter image description here

It’s a regular PDF. Note the file content length is around 290KB.

Attempting to download this file to Vue.JS frontend (using axios), I’ve tried the following 2 methods:

1.

First, I tried making use of npm library called js-file-download with the following code:

import fileDownload from "js-file-download";
const downloadAttachment = async (attachmentId, filename) => {
  try {
    var result = await api.post(`/api/Attachments/DownloadAttachment/${attachmentId}`);
    fileDownload(result.data, filename, result.headers.type);
  } catch (error) {
    console.error(error);
    return error;
  }
}

This code give’s me a broken PDF file, which has 2 blank pages (the original PDF has 2 pages of content) which appears to be roughly double the size it’s supposed to be:

enter image description here

2.

I also tried by creating a JavaScript blob (excluding the above mentioned library) with the following code:

const downloadAttachment = async (attachmentId, filename) => {
  try {
    var result = await api.post(`/api/Attachments/DownloadAttachment/${attachmentId}`);
    let blob = new File([result.data], filename, { type: result.headers["content-type"] });
    let exportUrl = URL.createObjectURL(blob);
    window.location.assign(exportUrl);
    URL.revokeObjectURL(exportUrl);
  } catch (error) {
    console.error(error);
    return error;
  }
}

File wise, this give’s me exactly the same broken 510kb file. Even console logging the blob shows a size of 522881 while the response from the api’s headers shows a content length of 297167:

enter image description here

I cannot figure out what is going on or where the extra data is coming from. The same happens to other file types such as excel files or images, though interestingly downloading very simple file types such as txt or csv files does not cause this issue.

How can I specify the data that I extract for my IDE to know the type of object they are, if possible in Javascript? React native

I have this custom component that I want to let them know that style is type of stylesheet and children type of children if possible in react native

For example:

import { StyleSheet, Text as TextReact } from "react-native";
import React from "react";

/**
 * This Text will have the font of 'serif and is customizable
 * @param {*} param0
 * @returns returns the text from react native with styles and string
 */
export function Text({ children, style }) {
  return <TextReact style={[styles.textStyle, style]}>{children}</TextReact>;
}

const styles = StyleSheet.create({
  textStyle: {
    fontFamily: "serif",
  },
});

I want to let them know style is an object from stylesheet for ide to know, so I don’t have to type all the styles manually and save at least some time (if possible lol)

I want to say like:

/**
 * This Text will have the font of 'serif and is customizable
 * @param {*: { style is typeof StyleSheet Object}} param0
 * @returns returns the text from react native with styles and string
 */

Like in this image:
Style type

Opening accordion link in a website scrolls everything up

So I made an accordion for FAQs for a website I am working on. Every time I click on a link(question) a content (answer) should show up.
Everything work as expected other than once I click on the link and when the content shows up the whole page scrolls up which makes it very annoying.

.FAQ {
  width: 100%;
  height: 80vh;
  background-color: var(--main);
  display: flex;
  align-items: center;
  justify-content: center;
}

.container3-5 {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
}

.accordion-item {
  background-color: #283042;
  border-radius: 4px;
  margin-bottom: 10px;
  padding: 10px;
  box-shadow: 5px 2px 5px rgba(0, 0, 0, .1);
}

.accordion-link {
  font-size: 25px;
  color: rgba(255, 255, 255, .8);
  text-decoration: none;
  background-color: #283042;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
}

.accordion-link ion-icon {
  color: #e7d5ff;
  padding: 5px;
}

.accordion-link .down {
  display: none
}

.answer {
  max-height: 0;
  overflow: hidden;
  position: relative;
  background-color: #212838;
  transition: max-height 650ms;
}

.answer::before {
  content: "";
  position: absolute;
  width: 6px;
  height: 90%;
  background-color: #8fc460;
  top: 50%;
  left: 0;
  transform: translateY(-50%);
}

.answer p {
  color: rgba(255, 255, 255, .6);
  font-size: 20px;
  padding: 20px;
}

.accordion-item:target .answer {
  max-height: 200px;
}

.accordion-item:target .up {
  display: none;
}

.accordion-item:target .down {
  display: block;
}
<div class="FAQ">
  <div class="container3-5">
    <h1>FAQs</h1>
    <div class="accordion">
      <div class="accordion-item" id="qestion1">
        <a class="accordion-link" href="#qestion1">
                        Question 1....?
                        <ion-icon class="up" name="arrow-forward-outline"></ion-icon>
                        <ion-icon class="down" name="arrow-down-outline"></ion-icon>
                    </a>
        <div class="answer">
          <p>
            Lorem ipsum dolor, sit amet consectetur adipisicing elit. Enim, facilis iure! At autem quasi exercitationem laudantium fugiat dolore esse. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Enim, facilis iure! At autem quasi exercitationem laudantium
            fugiat dolore esse.
          </p>

        </div>
      </div>
      <div class="accordion-item" id="qestion2">
        <a class="accordion-link" href="#qestion2">
                        Question 1....?
                        <ion-icon class="up" name="arrow-forward-outline"></ion-icon>
                        <ion-icon class="down" name="arrow-down-outline"></ion-icon>
                    </a>
        <div class="answer">
          <p>
            Lorem ipsum dolor, sit amet consectetur adipisicing elit. Enim, facilis iure! At autem quasi exercitationem laudantium fugiat dolore esse. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Enim, facilis iure! At autem quasi exercitationem laudantium
            fugiat dolore esse.
          </p>
        </div>
      </div>
      <div class="accordion-item" id="qestion3">
        <a class="accordion-link" href="#qestion3">
                        Question 1....?
                        <ion-icon class="up" name="arrow-forward-outline"></ion-icon>
                        <ion-icon class="down" name="arrow-down-outline"></ion-icon>
                    </a>
        <div class="answer">
          <p>
            Lorem ipsum dolor, sit amet consectetur adipisicing elit. Enim, facilis iure! At autem quasi exercitationem laudantium fugiat dolore esse. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Enim, facilis iure! At autem quasi exercitationem laudantium
            fugiat dolore esse.
          </p>
        </div>
      </div>
      <div class="accordion-item" id="qestion4">
        <a class="accordion-link" href="#qestion4">
                        Question 1....?
                        <ion-icon class="up" name="arrow-forward-outline"></ion-icon>
                        <ion-icon class="down" name="arrow-down-outline"></ion-icon>
                    </a>
        <div class="answer">
          <p>
            Lorem ipsum dolor, sit amet consectetur adipisicing elit. Enim, facilis iure! At autem quasi exercitationem laudantium fugiat dolore esse. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Enim, facilis iure! At autem quasi exercitationem laudantium
            fugiat dolore esse.
          </p>
        </div>
      </div>
      <div class="accordion-item" id="qestion5">
        <a class="accordion-link" href="#qestion5">
                        Question 1....?
                        <ion-icon class="up" name="arrow-forward-outline"></ion-icon>
                        <ion-icon class="down" name="arrow-down-outline"></ion-icon>
                    </a>
        <div class="answer">
          <p>
            Lorem ipsum dolor, sit amet consectetur adipisicing elit. Enim, facilis iure! At autem quasi exercitationem laudantium fugiat dolore esse. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Enim, facilis iure! At autem quasi exercitationem laudantium
            fugiat dolore esse.
          </p>
        </div>
      </div>
    </div>
  </div>

Timestamp always the same on node.js

I have a project under nuxt.js + expressjs and the timestamp is always the same (the moment at which I launch the project)

This issue occurs in development and production mode.

I tried many things like date.getTime or date.now and still the same problem

I am using a JAVASCRIPT library called p5js, I have experienced some odd errors before but I am genuinely confused this time [closed]

I am having issues when I click the Up Arrow or Down Arrow none of the code actually goes through, there is no response and error message.

Here is my code:

    function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  noStroke();
  noCursor();

  function keyPressed() {
      if (keyCode === UP_ARROW) {
        for (let x = 0; x<400, x++;) {
          triangle(20, 200+x, 23, 190+x, 28, 200+x);
        }
      } else if (keyCode === DOWN_ARROW) {
        triangle(20, 200-x, 6, 190-x, 20, 200-x);
      }
        
  }  
}

Check out the reference here:
p5js Reference

I am currently trying to build a sort of platformer video game and all help is appreciated!