how to wrap multiple arrays in a single one [duplicate]

In react I am using map functions to display some arrays from a database.
this is the code :

 <Flex >
      {allPrismicCollection.nodes.map((collection)=>
      (
        <Navbar>
        <NavTitle>{collection.data.collection.text}</NavTitle>
        <NavbarFlex>
        {collection.data.slides.map((coll)=>
        <>
          {coll.slide.document.data.blogs.map((s)=>
          <>
 {s.blog.document.data.tags.map((t)=>
              (
                <NavLink><Link to='#'>{t.tag}</Link></NavLink>
              )
            )}
            </>
          )}
          </>
        )}
        </NavbarFlex>
      </Navbar>
      )
      )}
    </Flex>

This code display this:
enter image description here
eventually this will return duplicated values in each table for example Popular section has duplicated values such as Entertainment , Happiness …
and if I console the s.blog.document.data.tags It will display :
enter image description here
It displays multiple arrays for each section , the only way I guess to solve the duplication is to wrap each section’s arrays into an array then eradicate the duplicated values , but I have no idea how to do that ! Any idea ?

Putting horizontal scrollbar in electron screenshot

So I’m currently implementing in Electron JS a program that takes a website screenshot and shows it on a new electron window. The thing is: For small screens, it does not show an horizontal scrollbar, so the user can’t move horizontally (in the image below, I’m opening in the new window the selected website, but there’s no horizontal scrollbar in the section where it shows the page).

enter image description here

Is there any way to show a horizontal scroll bar where the website screenshot is?

How to use vanilla js to count-up numbers with commas every second? [duplicate]

I have a predefined number in a div and would like it to go up every second. The below works. It’s nice and clean. The problem is I need the numbers to show commas.

Any clean solution?

<div id="numbersUP">500123</div> 
    function animateValue(id){ 
        var obj = document.getElementById(id);
        var current = obj.innerHTML;  

        
        setInterval(function(){
            obj.innerHTML = current++;
        }, 1000);
    }

    animateValue('numbersUP');

TypeError: Cannot read properties of undefined (reading ‘link’) in json

I’m trying to send a message containing link from json file, but if I update it – the code says
TypeError: Cannot read properties of undefined (reading 'link'), and it won’t see this link until I restart my code!

My sources.json file:

{
    "968": {
        "link": "1"
    },
    "970": {
        "link": "2"
    },
    "971": {
        "link": "3"
    },
    "972": {
        "link": "4"
    },
    "977": {
        "link": "5"
    },
    "979": {
        "link": "6"
    }
}

The code I’m using is:

const sources = require('../folder/sources')
let source = sources[number].link

Is there any way to fix it without restarting my bot all the time?

Best practice when using javascript local storage

I created this project using html/css/js:
https://codepen.io/caanton/pen/XWZwvqe

function saveLocalDone(todo){
var done
if (localStorage.getItem("done") === null){
  done = []
}else{
  done = JSON.parse(localStorage.getItem("done"))
}
done.push(todo)
localStorage.setItem("done", JSON.stringify(done))
location.reload();

I am looking for some help to get the best practice when using local storage. When I move a to-do element between sections I need to refresh the page to avoid some bugs. Lines 28 and 148 to be exact. Is there any other way to do it as I don t think refreshing the page every time an element move is efficient?

Thank you for your time

Unable to capture unload event

Ultimately, my goal is to clear localStorage if the user closes the browser or navigates to another page (not if they refresh the current page). I am just trying right now to capture the unload event using “beforeunload”, but I cannot get it to fire.

    window.addEventListener('beforeunload', function (e) {

    e.preventDefault();
    alert('Bye');
    
});

How to make react-window FixedSizeList scroll with the viewport instead of the component’s scroll bar?

I am trying to integrate react-window‘s FixedSizeList and FixedSizeGrid components to increase the initial rendering speed of my page. Is there some way for me to let the user scroll down the react-window component using the viewport’s scrolling area? I was also
wondering if there is some way to remove the scrollbar from the react-window component and only use the viewport’s scrolling as I described above.

I tried integrating the documentation version of FixedSizeList into my page and as you can see, since the total height of all my rows is greater than the height I specified in the component so the vertical scrollbar beside the component appears, which I want to remove. I also cannot figure out how to let scrolling downwards on the viewport make the react-window component scroll down the rest of its rows.

From looking online, I think I might need to modify the CSS style of the FixedSizeList to have overflow:hidden to remove the scrollbar but how can I ensure that I keep the scrolling functionality and that the user can scroll down the component from anywhere in the viewport?

Current version with no react-window

FixedSizeList version

  const Row = ({ index, style }) => (
    <div style={style}>Row {index}</div>
  );

  <FixedSizeList
      height={500}
      itemCount={38}
      itemSize={35}
      width={"100%"}
    >
      {Row}
    </FixedSizeList>

How Can I Pass a Parent Cookie into an iFrame src?

So I have embedded iFrame forms on my site and need to implement persistent tracking for users, meaning that their UTM parameters pass between pages and then get submitted into hidden fields with the form.

I believe the best way to do this is by setting a cookie to capture the UTM params on the parent site (done), and then reading the cookie to set a query string on the iFrame src. From there, I can pass the hidden values from the iFrame src (that’s also already done).

What I’m having trouble figuring out is how to connect the dots. and have searched around quite a bit without finding a clear answer. And I’m showing my work but certainly open to other suggestions.

So I have these code snippets…

First, just above the iFrame embed, there’s this:

const getCookie = (__gtm_campaign_url) =>{
  // Construct a RegExp object as to include the variable name
  const re = new RegExp(`(?<=${cookie_name}=)[^;]*`);
  try{
    return document.cookie.match(re)[0];    // Will raise TypeError if cookie is not found
  }catch{
    return "this-cookie-doesn't-exist";
  }
}

getCookie('__gtm_campaign_url') // 
getCookie('_non_existent') // this-cookie-doesn't-exist

Then, to generate the iFrame embed:

 var form = 'https://go.mysite.com/some-unique-ids';
 var params = window.location.search;      // I know this needs to change, just don't know how
 var thisScript = document.scripts[document.scripts.length - 1];
 var iframe = document.createElement('iframe');
 
 iframe.setAttribute('src', form + params);
 iframe.setAttribute('width', '100%');
 iframe.setAttribute('height', 500);
 iframe.setAttribute('type', 'text/html');
 iframe.setAttribute('frameborder', 0);
 iframe.setAttribute('allowTransparency', 'true');
 iframe.style.border = '0';
 
 thisScript.parentElement.replaceChild(iframe, thisScript);

Finally, within the iFrame, there’s this snippet to parse the cookie and get it into the proper hidden fields. Frankly, this is leftover from something else I’ve tried but didn’t work, so it could/should be eliminated if I could get the cookie parsed into var params = [foo] above, but including it for reference:

// Parse the Cookie
function getCookie('__gtm_campaign_url') {
    var name = __gtm_campaign_url + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
// Parse the URL inside Cookie
function getParameterByName(name) {
    name = name.replace(/[[]/, "\[").replace(/[]]/, "\]");
    var regex = new RegExp("[\?&]" + name + "=([^&#]*)");
    results = regex.exec(getCookie("__gtm_campaign_url"));
    return results === null ? "" : decodeURIComponent(results[1].replace(/+/g, " "));
}
// Pass the values to hidden field 
document.querySelector("input#input_3_9").value = getParameterByName('utm_source');  
document.querySelector("input#input_3_9").value = getParameterByName('utm_term');  
document.querySelector("input#836443_81170pi_836443_81170").value = getParameterByName('utm_medium');
document.querySelector("input#input_3_8").value = getParameterByName('utm_campaign');   
document.querySelector("input#input_3_11").value = getParameterByName('utm_content');

CSS Check If Element Is Overflowing Then Animate Back And Forth

I have some short and long text in html with max-width and overflow styles.
i want to check if an element is overflowing then start back and forth animation to users can see all contents.

Please see this demo:

.animated {
  position: relative;
  white-space: nowrap;
  max-width: 150px;
  overflow: hidden;
  background: #0c0c0c;
}

.text-animated{
  color: #fff;
  animation: backAndForth 5s linear infinite;
}

@keyframes backAndForth {
    0% { transform: translateX(0); }
    10% { transform: translateX(0); }
    45% { transform: translateX(calc(100% - 340px)); }
    55% { transform: translateX(calc(100% - 340px)); }
    90% { transform: translateX(0); }
    100% { transform: translateX(0); }
}
<div class="animated">
  <h3 class="text-animated">
    Some Short Text
  </h3>
</div>
<span>Must be fixed</span>

<br><br><br>

<div class="animated">
  <h3 class="text-animated">
    Some Long And Bigger Text To Animate
  </h3>
</div>
<span>Must be Animated to view all text</span>

Can anybody help me?

Thanks

TypeError: (0 , _footer).footerAdapter is not a function, nextjs unit testing

I am trying to test some nextjs code using the jest unit testing framework.

But I am getting this error.

TypeError: (0 , _footer).footerAdapter is not a function

Code:

    import { footerAdapter } from '../../components/Footer'

describe('footerAdapte1', () => {
    it('converts GraphQL JSON to Footer JSON2', () => {
        const graphql = `[{"attributes":{"items":{"title":"Our yagya","link":"/yagya","__typename":"ComponentFooterFooterItems"},"__typename":"Footer"},"__typename":"FooterEntity"},{"attributes":{"items":{"title":"Signup For Seva","link":"/Signup_For_Seva","__typename":"ComponentFooterFooterItems"},"__typename":"Footer"},"__typename":"FooterEntity"},{"attributes":{"items":{"title":" FAQ","link":"/ FAQ","__typename":"ComponentFooterFooterItems"},"__typename":"Footer"},"__typename":"FooterEntity"}]`
        const footerData = footerAdapter(JSON.parse(graphql))
        expect(footerData.length).toBe(9)
        expect(footerData[0].title).toBe("Our yagya")
    })
})

am I doing something wrong with this test?

Combine neighbouring items in a 3D Array into the biggest possible sized cuboids

I need to combine any neighbouring strings in the data array into the biggest possible sized cuboids

Visual example in 2D ( Each character represents a different string ). This would be split up into 3 different commands

O##      O                  ##
###  =>      and  #   and   ##
###               #         ##

(Reminder I need this, but in three dimensions)

function GenerateCommands() {
  var data: string[][][] = GetData();

  // Get the regions for the largest sized cuboid from data array
  // Command(startX, endX, startY, endY, startZ, endZ)
  // Repeat until all Every item in the data arr has been added
}

// x1: Start X
// x2: End X
// Etc..
function Command(x1, x2, y1, y2, z1, z2) {
  
}

(I hope i was able to explain this properly)

Why do Web Share shared files end up with a random name?

I’m using the navigator.share feature to share a PDF generated with jspdf. So far everything is working fine: the file is generated correctly with all the desired contents and it can be shared/downloaded without any major issue. The problem is that the document’s name is being changed to a random name, always in the form of “share”+bunchOfNumbers+”.pdf”, ignoring the defined name on the File creation.

The only posts I’ve found regarding this issue are Why web share API converts file name in random? and navigator.share api in android changes the name of the file that the user shares, and also this already closed bug, but none of them got any answer/resolution.

Here is my code to share the file:

if (navigator.canShare && navigator.userAgentData.mobile) {
  var pdf = new File([doc.output('blob')], doc_name + ".pdf", { type: "application/pdf" });
  var filesToShare = [pdf];

  try {
    navigator.share({ title: doc_name + ".pdf", files: filesToShare });
  } catch (error) {
    showBanner(error.message, bannerState.ERROR, ALERT_PARENT, ALERT_TIME);
  }
}

But I end up with this:

The name is correct on the title

enter image description here

But the pdf has a random name:

enter image description here

Any kind of help would be really appreciated!

Random numbers showing up and imeadietly dissapearing

I made a timer but for some reason, it sometimes switches to a number, and imeadetly switching back this also happens when the timer is done, when the interval has been removed.
ive tried to check if the interval variable was defined but it still happend
I use nextron (next.js)

import Head from "next/head";
import React from "react";
import { useState } from 'react';
import { NumberInput, ActionIcon, Button } from '@mantine/core';

import {
PlayerPlay,
PlayerPause,
PlayerStop,
} from "tabler-icons-react"

export default function Timer() {

const [input, setInput] = useState(0);

const [paused, setPaused] = useState(0);

const [running, setRunning] = useState(0);

const [time, setTime] = useState(0);

var interval;

if (running == 1) {
    if (interval == undefined) {
        interval = setInterval(() => {
            if (time > 0 && running == 1 && paused == 0) {
                setTime(time - 1)
            }
        }, 1000)
    } 

    if (time < 1) {
        clearInterval(interval)
        interval = undefined
        setRunning(0)
        setPaused(0)
        setInput(0)
        setTime(0)
    }
}

return (
    <React.Fragment>
        <Head>
            <title>Timer</title>
        </Head>
        <div>
        paused: {paused}
        <br/>
        running: {running}
        <br/>
        input: {input}
        <br/>
        time: {time}
        <NumberInput
            defaultValue={0}
            label="Time (in seconds)"
            radius="xl"
            hideControls
            value={input}
            onChange={(val) => {setInput(val); running == 0 ? setTime(val) : "ignore"}} 
        />
        <Button color="indigo" radius="xl" size="md" onClick={() => {setPaused(0); setRunning(1)}} disabled={running == 0 ? false : true }>Start</Button>
        <ActionIcon color="indigo" size="xl" radius="xl" variant="filled" disabled={running == 0? true : false} onClick={() => {paused == 0 ? setPaused(1) : setPaused(0)}}> { paused == 0 ? <PlayerPlay/> : <PlayerPause/> } </ActionIcon>
        <ActionIcon color="indigo" size="xl" radius="xl" variant="filled" disabled={running == 0? true : false} onClick={() => {setPaused(0); setRunning(0); setTime(input)}}> <PlayerStop/> </ActionIcon>
        </div>
    </React.Fragment>
)

}

Converting JSON array from one format to another using JavaScript

I’m a newbie here and would like some guidance. How do I convert the JSON array (input) to another JSON array but grouping by id and need just the values of ‘id’ and ‘sid’.

I have tried using lodash, array.reduce but couldn’t get the expected output.

The actual input will be a large JSON array and any suggestions on how to solve this efficiently will be much appreciated.

Input:

[
    {
        "id": "11111",
        "sid": "12345"
    },
    {
        "id": "22222",
        "sid": "23456"
    },
    {
        "id": "22222",
        "sid": "34567"
    }
]

Expected Output:

[
    {
        "11111": [
            "12345"
        ]
    },
    {
        "22222": [
            "23456",
            "34567"
        ]
    }
]

lodash:

_.groupBy(array, x => x.id);

lodash output:

{
  '11111': [
    { id: '11111', sid: '12345' }
  ],
  '22222': [
    { id: '22222', sid: '23456' },
    { id: '22222', sid: '34567' } 
  ]
}

array.reduce:

const groupById = (array, key, value) => {
  return array.reduce((result, currentValue) => {
    (result[currentValue[key]] = result[currentValue[key]] || []).push(
      currentValue[value]
    );
    return result;
  }, {});
};

array.reduce output:

{
    "11111": [
        "12345"
    ],
    "22222": [
        "23456",
        "34567"
    ]
}

HTML: How do I dynamically update text on a “shared” webpage based on which link is pressed

I have a list of workshop dates on my home page with links that direct users to the registration form/ page.

Everything on the registration page is static with the exception of the “date” and “location”.

How do I pass info from the home page to the registration page after the user clicks on the link?

Guessing I have to assign some values to the links? Not sure how.