VS Code TypeScript suggestions unexpected

Code examples:

export interface PluginMapWithParams {
  foo: {
    foo1?: string
    foo2?: number
  }
  bar: {
    bar1?: string
    bar2?: number
  }
}

export type PluginStyle1 = {
  [Name in keyof PluginMapWithParams]: [Name, PluginMapWithParams[Name]?]
}[keyof PluginMapWithParams]

export type PluginStyle2 = {
  [Name in keyof PluginMapWithParams]: { name: Name; params?: PluginMapWithParams[Name] }
}[keyof PluginMapWithParams]

export const pluginStyle1: PluginStyle1 = ['bar', {}]

export const pluginStyle2: PluginStyle2 = {
  name: 'bar',
  params: {},
}

pluginStyle1 suggestions shows all four params includes foo‘s. Besides, if you select foo1 or foo2, VS Code throws a type check error which is expected. But I prefer that VSCode doesn’t suggest foo1 and foo2.

pluginStyle2 works all as expected.

How can I make PluginStyle1‘s suggestions as same as PluginStyle2 or is it can not be done.

Metadata tags in Nextjs not recognized in google search

I’m working on a project built with Next.js and JavaScript. I tried to follow the Next.js documentation provided here (Optimizing: Metadata), which states that by declaring constants with metadata tags, it should automatically generate the Head section of the page containing the metadata declared in the constant. When inspecting the page locally, it works exactly as described. However, the issue is that Google doesn’t seem to correctly read this type of tag, so the title and description on my site were missing, and Google was reading random h2 tags.

Here’s an example of the page where I tried to insert the metadata:

// Metadata

export const metadata = {
  title: "MySite",
  description:
    "My site talks about this...",
};

//Layout//

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
          {children}
      </body>
    </html>
  );
}

Subsequently, I tried manually writing the Head tag on my page, adding title and description tags and including the declared variable inside them. After checking on Google, I discovered that this latter method works because Google correctly reads the title and description of the site. Here’s an example of how I modified the code:

// Metadata

export const metadata = {
  title: "MySite",
  description:
    "My site talks about this...",
};

//Layout//

export default function RootLayout({ children }) {
  return (
    <html>
        <Head>
        <title>{metadata.title}</title>
        <description>{metadata.description}</description>
        </Head>
      <body>
          {children}
      </body>
    </html>
  );
}

I wanted to ask if anyone else had encountered the same issue and had resolved it in a similar manner. The Next.js documentation doesn’t mention this problem because it should automate the creation of the Head and meta tags, but it seems that Google doesn’t accept it.

How do I use the cursor-based technique to do that in Redis after data is fetched from MongoDB?

My API is returning the same posts every time I hit the API from Redis, But how do I get new and different posts every time whenever I hit the API and data is stored in Redis?

How do I use the cursor-based technique to do that in Redis after data is fetched from MongoDB?

router.get('/posts', async (req, res) => {
  try {
    const cacheKey = `posts:${req.query.page || 1}`;
    const cacheTTL = 60;
    const cachedData = await redisClient.get(cacheKey);
    if (cachedData) {
      console.log('Data fetched from Redis cache');
      return res.json(JSON.parse(cachedData));
    }
    const result = await User.aggregate([
      { $project: { posts: 1 } },
      { $unwind: '$posts' },
      { $project: { postImage: '$posts.post', date: '$posts.date' } },
      { $sort: { date: -1 } },
      { $limit: 10 },
    ]);
    await redisClient.set(cacheKey, JSON.stringify(result), 'EX', cacheTTL);
    console.log('Data fetched from MongoDB and cached in Redis');
    res.json(result);
  } catch (err) {
    console.error(err);
  }
});

How do I create a function that takes length and width and finds the perimeter of a rectangle in JavaScript?

Engaging in the intricate realm of JavaScript, I embarked on a noble quest to forge a function of profound elegance. This formidable function, characterized by its remarkable ability to gracefully accept the crucial parameters of length and width, is meticulously designed to unlock the arcane secrets hidden within the geometry of rectangles. Yet, the labyrinthine twists and turns of code have, in their enigmatic complexity, proven to be a formidable challenge, far surpassing my initial expectations of ease and simplicity.

As I delved deeper into the code, its intricate architecture began to reveal its complexities, reminiscent of a grand symphony with a multitude of instruments playing in harmony. I found myself navigating through the labyrinth of JavaScript, meticulously orchestrating every line, every variable, and every function call. My pursuit of an efficient algorithm to calculate the perimeter, while seemingly straightforward on the surface, unfurled into a mesmerizing web of conditional statements, mathematical operations, and logical reasoning.

The journey to unlock the secrets of this seemingly humble rectangle’s perimeter has evolved into a profound exploration of the language’s capabilities and my own coding prowess. Although the path has been laden with challenges, I remain undeterred, resolute in my quest to conquer this coding conundrum and emerge with a solution that not only calculates the perimeter flawlessly but also exemplifies the artistry and craftsmanship that can be achieved in the realm of JavaScript programming.

Generate file object from content and send it to email using javascript

I have this file data

const ics = 'BEGIN:VCALENDARn' +
'VERSION:2.0n' +
'CALSCALE:GREGORIANn' +
'METHOD:PUBLISHn' +
'END:VCALENDARn';

i want to generate file object

where fileBody is ics data

convert(fileBody,filename)
{
      let fileContent=this.dataURLtoFile('data:text/plain;charset=utf-8,' + encodeURIComponent(fileBody),filename);
}

dataURLtoFile(dataurl, filename) {
  console.log('dataurl',dataurl);
  var arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }

  return new File([u8arr], filename, { type: mime });
}

but this is not converting to file

HTML Iframe Selection

I want to change the gallery images to iframes to be able to display 360 degrees images.
If one of the preview iframes is selected, i want it to appear in big in the highlight frame.
I created a code which works just fine for usual images, but i want to use the 360 degree images instead. What do i have to change to make it work?

This is my JAVASCRIPT-Code for the images, i want the images to be swapped to iframes

 function imageGallery(){
    const highlight = document.querySelector('.gallery-highlight2');
    const previews = document.querySelectorAll('.room-preview2 img');

    previews.forEach(preview => {
      preview.addEventListener("click", function(){
        const smallSrc = this.src;
        const bigSrc = smallSrc.replace("small", "big");
        highlight.src = bigSrc;
        previews.forEach(preview => preview.classList.remove("room-active2"));
        preview.classList.add("room-active2");
      });
    });
  }

  imageGallery();

This is my HTML-Code:

<div class="col-md-8">
        <div class="room-gallery2">
          <img src="img/wohnung/wohnzimmer/wohnzimmer_1.jpg" class="gallery-highlight2" alt="Foto Groß">
      <div class="room-preview2">
        <img src="img/wohnung/wohnzimmer/wohnzimmer_1.jpg" class="room-active2" alt="Foto 1">
        <img src="img/wohnung/wohnzimmer/wohnzimmer_2.jpg" alt="Foto 2">
        <img src="img/wohnung/wohnzimmer/wohnzimmer_3.jpg" alt="Foto 3">
        <img src="img/wohnung/wohnzimmer/wohnzimmer_4.jpg" alt="Foto 4">
      </div>
    </div>
  </div>

swiperjs in not made public

i use the swiperjs in a vuejs project.
Now, they told me that:

“your frame uses the swiper.js plugin, which unfortunately is not made public. This is important when it comes to frame mechanics such as: her scrolling, Using a ready-made library on the website will be most effective.”

What should i do now?

app.js

import 'swiper/css/navigation'
import 'swiper/css/pagination'
import VueAwesomeSwiper from 'vue-awesome-swiper'

Vue.use(VueAwesomeSwiper)

RegEx matches perfectly but skips matches when replacing

I have a text containing placeholders like %%%NAME.suffix|DefaultValue%%%.

The following RegEx is matching it perfectly (see link): %{3}((w+)(?:.(w+))?)(?:|([sS]*?))?%{3}

But it skips matches when I replace them one by one in JavaScript (ES5, same in ES6 or later) using a while loop.

I’m not using a RexEx pattern in String.replace(/a/gm, "b") but a simple string String.replace("%%%NAME.suffix|DefaultValue%%%", "DefaultValue").

var soup = "%%%X.x|a%%% %%%Y.y|b%%% %%%Z.z|c%%%";

var m;
while ((m = regex.exec(soup)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    console.log(m[2] + " found: " + JSON.stringify(m, null, 2));
    soup = soup.replace(m[0], m[4]);
}

Result: the Y placeholder is skipped. Why is that?

Output:

X found: [ "%%%X.x|a%%%", "X.x", "X", "x", "a" ]
Z found: [ "%%%Z.z|c%%%", "Z.z", "Z", "z", "c" ]

Also see full code here: https://runjs.co/s/IcNbKwSCu

Nothing is shown when coverting GSAP Javascript code to React

I’m trying to convert some JavaScript code to React. The code is for creating a horizontal scrollbar effect using GSAP.
I simply placed the GSAP code inside a useEffect hook to implement it. However, after doing this, nothing appears on the screen. What’s worse, no errors are showing up in the console, making it difficult to debug.Can you let me know why it doesn’t work on React code??
I’ll upload the JavaScript code and the React code shortly. The key parts to focus on are the main.js file and the useEffect hook in the React code. And also attach codesandbox link each

Javascript
index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="wrapper">
      <div class="container scrollx">
        <svg
          viewBox="0 0 900 10"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            d="M9.89998 6C9.43671 8.28224 7.41896 10 5 10C2.23858 10 0 7.76142 0 5C0 2.23858 2.23858 0 5 0C7.41896 0 9.43671 1.71776 9.89998 4H445.1C445.563 1.71776 447.581 0 450 0C452.419 0 454.437 1.71776 454.9 4H890.1C890.563 1.71776 892.581 0 895 0C897.761 0 900 2.23858 900 5C900 7.76142 897.761 10 895 10C892.581 10 890.563 8.28224 890.1 6H454.9C454.437 8.28224 452.419 10 450 10C447.581 10 445.563 8.28224 445.1 6H9.89998Z"
            fill="#D9D9D9"
          />
          <mask
            id="mask0_0_1"
            style="mask-type: alpha;"
            maskUnits="userSpaceOnUse"
            x="0"
            y="0"
            width="900"
            height="10"
          >
            <path
              d="M9.89998 6C9.43671 8.28224 7.41896 10 5 10C2.23858 10 0 7.76142 0 5C0 2.23858 2.23858 0 5 0C7.41896 0 9.43671 1.71776 9.89998 4H445.1C445.563 1.71776 447.581 0 450 0C452.419 0 454.437 1.71776 454.9 4H890.1C890.563 1.71776 892.581 0 895 0C897.761 0 900 2.23858 900 5C900 7.76142 897.761 10 895 10C892.581 10 890.563 8.28224 890.1 6H454.9C454.437 8.28224 452.419 10 450 10C447.581 10 445.563 8.28224 445.1 6H9.89998Z"
              fill="#D9D9D9"
            />
          </mask>
          <g mask="url(#mask0_0_1)">
            <rect class="mask" y="-49" height="99" fill="black" />
          </g>
        </svg>

        <section class="sec1 pin">
          <span>Advanced</span>
          <h1>Signify Elegance</h1>

          <div class="col">
            <p>
              Lorem ipsum dolor sit amet consectetur. Egestas euismod nec sit
              sed massa turpis in. Sit praesent arcu leo lectus pellentesque.
              Ornare elit orci morbi volutpat. Ut fermentum lorem morbi quis
              risus amet urna. Urna egestas lorem.
            </p>
            <p>
              Lorem ipsum dolor sit amet consectetur. Egestas euismod nec sit
              sed massa turpis in. Sit praesent arcu leo lectus pellentesque.
              Ornare elit orci morbi volutpat. Ut fermentum lorem morbi quis
              risus amet urna. Urna egestas lorem.
            </p>
          </div>
        </section>
        <section class="sec2 pin">
          <span class="anim">Advanced</span>
          <h1 class="anim">Signify Elegance</h1>

          <div class="col anim">
            <p>
              Lorem ipsum dolor sit amet consectetur. Egestas euismod nec sit
              sed massa turpis in. Sit praesent arcu leo lectus pellentesque.
              Ornare elit orci morbi volutpat. Ut fermentum lorem morbi quis
              risus amet urna. Urna egestas lorem.
            </p>
            <p>
              Lorem ipsum dolor sit amet consectetur. Egestas euismod nec sit
              sed massa turpis in. Sit praesent arcu leo lectus pellentesque.
              Ornare elit orci morbi volutpat. Ut fermentum lorem morbi quis
              risus amet urna. Urna egestas lorem.
            </p>
          </div>
        </section>
        <section class="sec3 pin">
          <span class="anim">Advanced</span>
          <h1 class="anim">Signify Elegance</h1>

          <div class="col anim">
            <p>
              Lorem ipsum dolor sit amet consectetur. Egestas euismod nec sit
              sed massa turpis in. Sit praesent arcu leo lectus pellentesque.
              Ornare elit orci morbi volutpat. Ut fermentum lorem morbi quis
              risus amet urna. Urna egestas lorem.
            </p>
            <p>
              Lorem ipsum dolor sit amet consectetur. Egestas euismod nec sit
              sed massa turpis in. Sit praesent arcu leo lectus pellentesque.
              Ornare elit orci morbi volutpat. Ut fermentum lorem morbi quis
              risus amet urna. Urna egestas lorem.
            </p>
          </div>
        </section>
      </div>
    </div>
    <script src="main.js"></script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"
      integrity="sha512-16esztaSRplJROstbIIdwX3N97V1+pZvV33ABoG1H2OyTttBxEGkTsoIVsiP1iaTtM8b3+hu2kB6pQ4Clr5yug=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    ></script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollToPlugin.min.js"
      integrity="sha512-v/m68W+vaGN/6igoyFpd4GlQzu0jx9/n5gr2PKq5vif+RObyGKHse384YHrOULaxZ810XhlHUrmB3U8UnPB19Q=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    ></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js"></script>
  </body>
</html>

main.js

const sections = gsap.utils.toArray(".container section");

const mask = document.querySelector(".mask");

let scrollTween = gsap.to(sections, {
  xPercent: -100 * (sections.length - 1),
  ease: "none",
  scrollTrigger: {
    trigger: ".container",
    pin: true,
    scrub: 1,
    end: "+=3000"
  }
});

React
App.js

import React, { useEffect, useRef } from "react";
import { Globalstyle, Wrap } from "./styles";
import { gsap, ScrollTrigger } from "gsap/all";

gsap.registerPlugin(ScrollTrigger);

const App = () => {
  const containerRef = useRef(null);
  const maskRef = useRef(null);

  useEffect(() => {
    const sections = gsap.utils.toArray(
      containerRef.current.querySelectorAll("section")
    );

    const mask = maskRef.current;

    let scrollTween = gsap.to(sections, {
      xPercent: -100 * (sections.length - 1),
      ease: "none",
      scrollTrigger: {
        trigger: containerRef.current,
        pin: true,
        scrub: 1,
        end: "+=3000"
      }
    });
  }, []);

  return (
    <>
      <Globalstyle />
      <Wrap>
        <div className="wrapper">
          <div className="container scrollx" ref={containerRef}>
            <svg
              viewBox="0 0 900 10"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M9.89998 6C9.43671 8.28224 7.41896 10 5 10C2.23858 10 0 7.76142 0 5C0 2.23858 2.23858 0 5 0C7.41896 0 9.43671 1.71776 9.89998 4H445.1C445.563 1.71776 447.581 0 450 0C452.419 0 454.437 1.71776 454.9 4H890.1C890.563 1.71776 892.581 0 895 0C897.761 0 900 2.23858 900 5C900 7.76142 897.761 10 895 10C892.581 10 890.563 8.28224 890.1 6H454.9C454.437 8.28224 452.419 10 450 10C447.581 10 445.563 8.28224 445.1 6H9.89998Z"
                fill="#D9D9D9"
              />
              <mask
                id="mask0_0_1"
                style={{ maskType: "alpha" }}
                maskUnits="userSpaceOnUse"
                x="0"
                y="0"
                width="900"
                height="10"
              >
                <path
                  d="M9.89998 6C9.43671 8.28224 7.41896 10 5 10C2.23858 10 0 7.76142 0 5C0 2.23858 2.23858 0 5 0C7.41896 0 9.43671 1.71776 9.89998 4H445.1C445.563 1.71776 447.581 0 450 0C452.419 0 454.437 1.71776 454.9 4H890.1C890.563 1.71776 892.581 0 895 0C897.761 0 900 2.23858 900 5C900 7.76142 897.761 10 895 10C892.581 10 890.563 8.28224 890.1 6H454.9C454.437 8.28224 452.419 10 450 10C447.581 10 445.563 8.28224 445.1 6H9.89998Z"
                  fill="#D9D9D9"
                />
              </mask>
              <g mask="url(#mask0_0_1)">
                <rect
                  className="mask"
                  y="-49"
                  height="99"
                  fill="black"
                  ref={maskRef}
                />
              </g>
            </svg>
            <section className="sec1 pin">
              <span>Advanced</span>
              <h1>Signify Elegance</h1>

              <div className="col">
                <p>
                  Lorem ipsum dolor sit amet consectetur. Egestas euismod nec
                  sit sed massa turpis in. Sit praesent arcu leo lectus
                  pellentesque. Ornare elit orci morbi volutpat. Ut fermentum
                  lorem morbi quis risus amet urna. Urna egestas lorem.
                </p>
                <p>
                  Lorem ipsum dolor sit amet consectetur. Egestas euismod nec
                  sit sed massa turpis in. Sit praesent arcu leo lectus
                  pellentesque. Ornare elit orci morbi volutpat. Ut fermentum
                  lorem morbi quis risus amet urna. Urna egestas lorem.
                </p>
              </div>
            </section>
            <section className="sec2 pin">
              <span className="anim">Advanced</span>
              <h1 className="anim">Signify Elegance</h1>

              <div className="col anim">
                <p>
                  Lorem ipsum dolor sit amet consectetur. Egestas euismod nec
                  sit sed massa turpis in. Sit praesent arcu leo lectus
                  pellentesque. Ornare elit orci morbi volutpat. Ut fermentum
                  lorem morbi quis risus amet urna. Urna egestas lorem.
                </p>
                <p>
                  Lorem ipsum dolor sit amet consectetur. Egestas euismod nec
                  sit sed massa turpis in. Sit praesent arcu leo lectus
                  pellentesque. Ornare elit orci morbi volutpat. Ut fermentum
                  lorem morbi quis risus amet urna. Urna egestas lorem.
                </p>
              </div>
            </section>
            <section className="sec3 pin">
              <span className="anim">Advanced</span>
              <h1 className="anim">Signify Elegance</h1>
              <div className="col anim">
                <p>
                  Lorem ipsum dolor sit amet consectetur. Egestas euismod nec
                  sit sed massa turpis in. Sit praesent arcu leo lectus
                  pellentesque. Ornare elit orci morbi volutpat. Ut fermentum
                  lorem morbi quis risus amet urna. Urna egestas lorem.
                </p>
                <p>
                  Lorem ipsum dolor sit amet consectetur. Egestas euismod nec
                  sit sed massa turpis in. Sit praesent arcu leo lectus
                  pellentesque. Ornare elit orci morbi volutpat. Ut fermentum
                  lorem morbi quis risus amet urna. Urna egestas lorem.
                </p>
              </div>
            </section>
          </div>
        </div>
      </Wrap>
    </>
  );
};

export default App;

CodeSandBox
Javascript
https://codesandbox.io/s/horizontal-scroll-rxg8md?file=/index.html:0-4915&resolutionWidth=1400&resolutionHeight=800

React
https://codesandbox.io/s/horizontal-scroll-xv7hzj?file=/src/App.js&resolutionWidth=1400&resolutionHeight=800

Why doesn’t my popup window appear on my vocabulary page if the answer is correct?

I’m pretty new to Javascript and can’t get any further at the moment.
I have created a vocabulary page that works quite well so far.
Now I wanted to make a popup window appear when answering correctly.

HTML

<main>
        <form onsubmit="compare(); return false;">

            <div class="flag">
                <a href="vocabularytest.html"><img src="img/EngFlag.png"></a>
                <img src="img/SpaFlag.jpg">
                <img src="img/FraFlag.jpg">
            </div>    
            <div class="TestText">
                <h4>Was bedeutet...</h4>
                <h2 id="word"></h2>
            </div>
            <div class="vokabelTest-germ">
                <input required type="text" id="germanTestText" placeholder="Deutsch ...">
                <label for="germanTestText"></label>
            </div>
            <div class="btnTest-cont">
                <button onclick="openPopUp()">Überprüfen
                    <span class="material-symbols-outlined">task_alt</span>
                </button>
                </div>
        
        </form> 
        
        <div class="popup" id="popup">
            <span class="material-symbols-outlined">check</span>
            <h2 id="compareText">Super :)</h2>
            <h4>weiter so...</h4>
            <button type="button">OK</button>
        </div>
</main> 

CSS

.popup {
    position: absolute;
    top: 0;
    right: 20px;
    width: 250px;
    height: 250px;
    background: var(--primary-color-light);
    text-align: center;
    border-radius: 20px;
    transform: scale(0.1);
    visibility: hidden;
    transition: 0.4s, top 0.4s;
}

.open-popup {
    top: 180px;
    transform: scale(1);
    visibility: visible;
}

JavaScript

let dictionaryEng = JSON.parse(localStorage.getItem("dictionaryEng")) || {};
let randomGermanWord;
let popUp = document.querySelector("#popup");

function addVocabulary() {
    dictionaryEng[germanText.value] = englishText.value;

    germanText.value = '';
    englishText.value = '';

    localStorage.setItem("dictionaryEng", JSON.stringify(dictionaryEng));
    render();
}

function render() {
    vocabularyList.innerHTML = '';
    for (let key in dictionaryEng) {
    vocabularyList.innerHTML += `<li>${key} -> ${dictionaryEng[key]}</li>`;
    }
}

function nextVocabulary() {
    let obj_keys = Object.keys(dictionaryEng);
    randomGermanWord = obj_keys[Math.floor(Math.random() * obj_keys.length)];
    word.innerHTML = `${dictionaryEng[randomGermanWord]}?`;
}

function compare() {
    if (germanTestText.value == randomGermanWord) {
        openPopUp();
    } else {
        compareText.innerHTML = 'Falsch!!!';
    }
    germanTestText.value = '';
    nextVocabulary();
}

function openPopUp() {
    popUp.classList.add(".open-popup");
}

In the beginning I didn’t have the h2 element in the popup container and in the If statement I had to stand compareText… and it worked.

enter image description here
enter image description here

In the browser console, the CSS class is also added, but the pop-up window does not appear.

Maybe someone can help me out?
Please excuse my English, it’s just Google Translate.

Splice within for loop not removing selected indexes

If page reloaded, splice method returned [0]{‘C’} instead of 0:{‘B’}

todos = [0:{"title":"A"}, 1:{"title":"B"}, 2:{"title":"C"}] //store todos - localStorage
deletedTodo = [0,2] // remove A & C from todos - store removed element index - localStorage
window.addEventListener("load", (e) => {
  todos = JSON.parse(localStorage.getItem("todos")) || [];
  clearTodo();
});

function for checking deleted indexes that should removed from todos object then return updated todos object
otherwise return display Todos()

function clearTodo() {
  if (
    JSON.parse(localStorage.getItem("deletedTodo")) &&
    JSON.parse(localStorage.getItem("deletedTodo")).length > 0
  ) {
    for (
      let index = 0;
      index <= JSON.parse(localStorage.getItem("deletedTodo")).length;
      index++
    ) {
      todos.splice(JSON.parse(localStorage.getItem("deletedTodo"))[index], 1);
    }
    localStorage.setItem("todos", JSON.stringify(todos));

    localStorage.setItem("deletedTodo", JSON.stringify([]));
    deletedIndexex = [];

    return displayTodos();
  } else {
    return displayTodos();
  }
}

How could I duplicate an existing row in DevExpress MVC GridView?

I’m working in a large web app written in C# and JavaScript with DevExpress MVC controls. We are using a GridView to display a table with data:

GridView screenshot

I am trying to implement a function that will duplicate the currently selected row with all of its values. The function will be triggered by the button on the toolbar up top as illustrated on the screenshot.

Here is the code (truncated a bit) for the button:

public static void ConfigureGridViewToolbarSettings(GridViewSettings settings, TableViewModel model, HtmlHelper<TableViewModel> helper) {
            settings.Toolbars.Add(tb =>
            {
                tb.EnableAdaptivity = true;
                tb.Name = "GridViewToolBar";
                tb.Enabled = true;
                tb.Position = GridToolbarPosition.Top;
                tb.SettingsAdaptivity.EnableCollapseRootItemsToIcons = true;
                tb.SettingsAdaptivity.Enabled = true;

                var userAccessType = model.UserAccess.GetAccessType();


                    tb.Items.Add(i =>
                    {
                        i.AdaptivePriority = 1;
                        i.Text = "Duplicate Row";

                        if (userAccessType == UserAccessType.Contributor && !model.Table.ContributorCanAddRows)
                            i.Enabled = false;
                        else
                        {
                            i.Enabled = true;
                            i.ItemStyle.CssClass = "GridViewNewRow";
                            i.NavigateUrl = "javascript:ToolbarFunctions.DuplicateRow();";
                        }
                        i.Command = GridViewToolbarCommand.Custom;
                        i.ItemStyle.BackColor = Color.FromArgb(248, 249, 250);
                        i.Image.IconID = DevExpress.Web.ASPxThemes.IconID.EditCopy16x16;
                        i.ToolTip = "Duplicate the selected row";
                    });
                }
       }
}

My attempts so far have been unsucessful:

This code below is the JS method that is supposed to:

  1. Copy all the current values of the selected row
  2. Create a new row and fill in the cells with the values

What was happening:

  1. A lot of ‘foo() is not a function’ in debugging (ex. e.rowValues[EDM.Table.Grid.LastSelectedColumn.index];)
  2. I could not extract the columns’ field values either (for loop in the example below), even though those appear like they should be an object with “fieldName” value inside.
  3. I was easily able to add a new empty row.
DuplicateRow: function (s, e) {

        var keys = TableDataGridView.GetSelectedKeysOnPage();
        var selectedRow = TableDataGridView.GetRow(keys[0]);
        var columns = TableDataGridView.columns;
        //var rowValue = e.rowValues[EDM.Table.Grid.LastSelectedColumn.index];

        var i = 0;
        var key = TableDataGridView.GetRowKey(selectedRow );
        var fieldNames = [];

        for (var column in columns) {
            fieldNames.join(";", column.fieldName);
        }

        var rowData = TableDataGridView.GetRowValues(keys[0], fieldNames, onCallbackMultiValues);

        // Step 2: Create a new row with the same data
        var newRow = {};
        for(var i = 0; i < columns.length; i++) {
            newRow[columns[i]] = rowData[i];
        }

        // Step 3: Insert the new row into the MVCxClientGridView
        TableDataGridView.AddNewRow(newRow);
}

why process.env.UV_THREADPOOL_SIZE doesn’t work?

const crypto = require("crypto");
const start = Date.now();
process.env.UV_THREADPOOL_SIZE = 5;
for (let index = 0; index < 5; index++) {
  crypto.pbkdf2("password", "salt", 100000, 512, "sha512", () => {
    console.log(Date.now() - start);
  });
}

/*
outputs
1429
1518
1521
1537
2289

*/
`
// the outputs don’t seem to expected outputs. what is problem ?

how do I add the functionality to strike through the content in my To-Do-List?

I am creating a To-Do-List, using express and ejs. I want to add functionality in my To-Do-List that when I check the checkbox, I want that particular content striked-through.
To-Do-List snip

Firstly, I tried getting the value of the checkbox through body-parser, save it in a variable and then pass it on to my index.ejs file. I tried using the variable on in the EJS file but it didn’t work.
I eventually console logged the variable and then I saw that the value which was display was “undefined”.

import express from "express";
import bodyParser from "body-parser";

const app = express();
const port = 3000;
const Item = [];


app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));


app.get('/',(req,res)=>{
    res.render("index.ejs",{Item})
})

app.post('/submit',(req,res)=>{
    const {Item: newData} = req.body;
    const checked = req.body["check"];
    Item.push(newData)
    res.render("index.ejs",{Item,checked})
    console.log(checked)
})
app.listen(port,()=>{
    console.log("Server is running on port",port);
})


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="styles.css" />
    <title>ToDoList</title>
  </head>
  <body>
    <div class="container">
      <form action="/submit" method="POST">
        <input
          type="text"
          placeholder="New Item"
          name="Item"
          class="input-area"
          required
        />
        <input type="submit" class="btn" value="Add" />
      </form>
    </div>
    <% Item.forEach(item => { %>
    <div class="container-2">
      <input type="checkbox" class="checkBox" name="check" required />
      <%= item %>
    </div>
    <% }) %>
  </body>
</html>