How to format a credit card number to a specific format using Regex in JavaScript?

class User {
  #c;
  constructor(username, card) {
    this.u = username;
    this.#c = card;
  }
  get showData() {
    let regexFormat = /d{4}-d{4}-d{4}-d{4}/;
    // How can I convert this.#c to credit card format if it's not already formatted?
    return `Hello ${this.u} Your Credit Card Number Is ${this.#c}`;
  }
}
// Do Not Edit Anything Below

let userOne = new User("Osama", "1234-5678-1234-5678");
let userTwo = new User("Ahmed", "1234567812345678");
let userThree = new User("Ghareeb", 1234567812345678);

console.log(userOne.showData);
// Hello Osama Your Credit Card Number Is 1234-5678-1234-5678

console.log(userTwo.showData);
// Hello Ahmed Your Credit Card Number Is 1234-5678-1234-5678

console.log(userThree.showData);
// Hello Ghareeb Your Credit Card Number Is 1234-5678-1234-5678

console.log(userOne.c); // Prevent Accessing To Card Property Here
// Undefined

How can I use Regex in let regexFormat to convert the #c property into the credit card format ####-####-####-#### when it’s not already formatted, such as when it’s provided as a plain number or a continuous string without dashes?

How to pass an object into a class that references other objects to change their values

I am making an idle game library for my use and I am unsure how to go about creating a system that takes pairs of resources and amounts, checks if they are available, and if so then adjust all the values. Accessing the said resources and putting them in an object to pass into Building() is quite hard.

class Building extends Thing(){
    constructor(amount, tag, requirements){
        super(amount, tag)
        this.requirements = requirements
        /*
        This is roughly the shape of the input. It is the reference to the resources and the respective amounts needed.
        requirements = {
            player.resources.red: 5,
            player.resources.blue: 92,
        }
        */
    }

    buy(){
        // Check if each of the required resources are avaliable
        for(let resource of requirements){
            if(resource.amount >= resourceNeeded){
                continue
            }else{
                //Break the loop and return false, signaling that you cant buy this right now.
                return false
            }
        }
        // If you can buy it then go through each of the required resources and decrement them.
        for(let resource of requirements){
            if(resource.amount >= resourceNeeded){
                resource.amount -= resourceNeeded
            }
        }
        this.amount += 1
    }
}

For context a Thing or Resource has this structure:

resource:{
   amount: x,
   tag: "#tag", //Used for rendering on the page
}

The player object has this structure

player:{
   resources:{
      red: {
         amount: 3,
         tag: "#red"
   },
      blue: {
        amount: 4,
        tag: "#blue"
   },
   buildings:{
      purple: {
         amount: 0,
         tag: "#purple",
         requirements: "data structure",
      }
   },
}

Export all pages in Google Sheets to PDF

This is the function we use to export the content of a Google Sheets file to a PDF file in Drive:

function createPDF(ssId, sheet, pdfName, folder) {
  /**
   * Creates a PDF for the customer invoice template sheet
   * @param {string} ssId - Id of the Google Spreadsheet
   * @param {object} sheet - Sheet to be converted as PDF
   * @param {string} pdfName - File name of the PDF being created
   * @return {file object} PDF file as a blob
   */
  const fr = 0, fc = 0, lc = 9, lr = 27;
  const url = "https://docs.google.com/spreadsheets/d/" + ssId + "/export" +
    "?format=pdf&" +
    "size=A4&" +
    'fitw=true&' +                        // fit to page width, false for actual size
    "fzr=true&" +
    "portrait=true&" +
    "fitw=true&" +
    "gridlines=false&" +
    "printtitle=false&" +
    "top_margin=0.5&" +
    "bottom_margin=0.25&" +
    "left_margin=0.5&" +
    "right_margin=0.5&" +
    "sheetnames=false&" +
    "pagenum=UNDEFINED&" +
    "attachment=true&" +
    "gid=" + sheet.getSheetId() + '&' +
    "r1=" + fr + "&c1=" + fc + "&r2=" + lr + "&c2=" + lc;

  const params = { method: "GET", headers: { "authorization": "Bearer " + ScriptApp.getOAuthToken() } };
  const blob = UrlFetchApp.fetch(url, params).getBlob().setName(pdfName)

  const pdfFile = folder.createFile(blob)
  return pdfFile
}

This code works fine but only exports the first page. There are 2 pages in the Google Sheet. How is it possible to export both of them? Using the GUI it’s easy…

java HttpClient is adding the url to a post request automatically, how do I stop this?

constructor(private http: HttpClient, private router:Router)
this.http.post(:3000/login?user=${username}&pass=${password}, {user: username, pass: password}).subscribe((res: any)
this should send a post request to blank url port 3000 instead this is what the post request becomes http://159.203.71.147/:3000/login?user=Aaron&pass=Aaron. If I can stop the automatic addition of the address or stop the last slash from being added this would work. I have tested the api request without the slash with postman and it works correctly

I also tried typing the whole url in the string and it still adds on the url again

How can I sort an array?

I have a backend in node.js, where I generate this array –

let allItems = Array.from({ length: 1_000_000 }, (_, index) => ({
    id: index + 1,
    title: `Title ${index + 1}`,
    isSelected: false,
}));

On frontend I use react and dnd-kit to sort objects through drag and drop and I can also search by title.

Whole process and bug is displayed on pictures:enter image description here

enter image description here
enter image description here

enter image description here
enter image description here

After I typed in a string to search by,
selected by double tapping and dnd,
cleared my search, that array on backend changes to a new array where the first elements are search results, but it should be relative to search results, kind of like this –
if I dragged object 33 before object 3, it should be between object 2 and object 3.

This is a handler that sorts this array and saves to backend one –

app.put('/items', (req, res) => {
    const items = req.body.items;

    const updatedIds = new Set(items.map((item) => item.id));

    const updatedItems = items.map((updatedItem) => {
        const existingItem = allItems.find((item) => item.id === updatedItem.id);
        return {
            ...existingItem,
            ...updatedItem,
        };
    });

    const remainingItems = allItems.filter((item) => !updatedIds.has(item.id));

    const mergedItems = [...remainingItems];

    for (const updatedItem of updatedItems) {
        const index = items.findIndex((item) => item.id === updatedItem.id);
        if (index !== -1) {
            mergedItems.splice(index, 0, updatedItem);
        }
    }

    allItems = mergedItems;
    res.status(200).send({ message: 'Items updated successfully' });
});

Pls, I worked on this problem for 2 days and I finally decided to ask here

Javascript getElementsByClassName Collection Count is decreasing automatically

I have a main div and inside this, I have 3 child div. What I want is to get all 3 child div on Body Onload function and change their appearance through class attribute.

My code is like this:

Html is:

<div class="w-100 vh-100" id="main-grid">
            <div class="border border-dark grid-section" ></div>
            <div class="border border-dark grid-section">
                <div class="py-5 border border-danger d-flex justify-content-center align-items-center h-100">
                    <div>
                        <h2 class="text-primary" id="select-action">Select Form Action</h2>
                        <div class="list-group">
                            <button type="button" class="list-group-item list-group-item-action" aria-current="true" onclick="ChangeView(this)"><span class="me-2"><i class="fa-solid fa-circle-chevron-right" style="color: #74C0FC;"></i></span> Sum of Natural Numbers</button>
                            <button type="button" class="list-group-item list-group-item-action" onclick="ChangeView(this)"><span class="me-2"><i class="fa-solid fa-circle-chevron-right" style="color: #74C0FC;"></i></span>Factorial Calculation</button>
                            <button type="button" class="list-group-item list-group-item-action" onclick="ChangeView(this)"><span class="me-2"><i class="fa-solid fa-circle-chevron-right" style="color: #74C0FC;"></i></span>Multiplication Table</button>
                            <button type="button" class="list-group-item list-group-item-action" onclick="ChangeView(this)"><span class="me-2"><i class="fa-solid fa-circle-chevron-right" style="color: #74C0FC;"></i></span>Count Digits in a Number</button>
                            <button type="button" class="list-group-item list-group-item-action" onclick="ChangeView(this)"><span class="me-2"><i class="fa-solid fa-circle-chevron-right" style="color: #74C0FC;"></i></span>Reverse a Number</button>
                            <button type="button" class="list-group-item list-group-item-action" aria-current="true" onclick="ChangeView(this)"> <span class="me-2"><i class="fa-solid fa-circle-chevron-right" style="color: #74C0FC;"></i></span>Sum of Digits</button>
                            <button type="button" class="list-group-item list-group-item-action" onclick="ChangeView(this)"><span class="me-2"><i class="fa-solid fa-circle-chevron-right" style="color: #74C0FC;"></i></span>Print Even Numbers</button>
                            <button type="button" class="list-group-item list-group-item-action" onclick="ChangeView(this)"><span class="me-2"><i class="fa-solid fa-circle-chevron-right" style="color: #74C0FC;"></i></span>Print Odd Numbers</button>
                            <button type="button" class="list-group-item list-group-item-action" onclick="ChangeView(this)"><span class="me-2"><i class="fa-solid fa-circle-chevron-right" style="color: #74C0FC;"></i></span>Sum of Even Numbers</button>
                            <button type="button" class="list-group-item list-group-item-action" onclick="ChangeView(this)"><span class="me-2"><i class="fa-solid fa-circle-chevron-right" style="color: #74C0FC;"></i></span>Sum of Odd Numbers</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="border border-dark grid-section"></div>
          </div>

Javascript is:

function setInitialView()
{
    if(mainGrid)
        {
            var columns = mainGrid.getElementsByClassName("grid-section");
            if(columns !=null && columns.length == 3)
            {
                try{
                      columns[0].setAttribute("class", "d-none" );
                      columns[1].setAttribute("class", "d-block" );
                      columns[2].setAttribute("class", "d-none" );
                }
                catch(e)
                {
                   
                }
                let check=false;
            }
        }
}

Issue is:

In columns collection I get 3 child div as expected. But when I try to set class attribute of child it remove one child from columns list.
when “columns[0].setattribute” is called columns.Length becomes 2
when “columns[1].setattribute” is called columns.length becomes 1
and when last one is called columns[2] becomes null and thus throws exception.

I am not getting why collection is getting updated.

Please guide.

“Why is the object passed through Link state in React undefined when accessed via useLocation on the next page?”

I’m having trouble passing an object through the Link state in React Router, and it’s coming up as undefined when I try to access it on the next page using useLocation. Here’s a breakdown of my setup and the issues I’m encountering.

  1. Staff Component (Staff.js)

I’m fetching staff data from an API and rendering it with React Router’s Link:

import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';

const Staff = () => {
  const [staffMembers, setStaffMembers] = useState([]);

  useEffect(() => {
    // Fetch staff data from API
    fetch('https://api.example.com/staff')
      .then(response => response.json())
      .then(data => setStaffMembers(data))
      .catch(error => console.error('Error fetching staff:', error));
  }, []);

  return (
    <div className="hidden p-5 md:grid md:grid-cols-4 gap-6">
      {staffMembers.map((staff) => (
        <Link
          key={staff.id}
          to={{
            pathname: `/staff/${staff.title.replace(/s+/g, '-')}`,
            state: { staff } // Pass the entire staff object here
          }}
          className="image-div shadow hover:shadow-lg text-center rounded flex flex-col items-center border-l-8 border-yellow-200 p-3"
        >
          {staff.title_logo ? (
            <img src={staff.title_logo} alt={staff.title} className="w-16 h-16" />
          ) : (
            <div className="w-16 h-16 bg-gray-300 flex items-center justify-center">
              <span>No Logo Available</span>
            </div>
          )}
          <span className='mb-2 font-semibold text-lg'>{staff.title}</span>
        </Link>
      ))}
    </div>
  );
};

export default Staff;

  1. Staff Detail Component (StaffDetail.js)

I’m trying to access the passed staff object using useLocation:

import React from 'react';
import { useLocation } from 'react-router-dom';

const StaffDetail = () => {
  const location = useLocation();
  const staff = location.state?.staff; // Attempt to access the staff object

  console.log('Location:', location); // Log the entire location object
  console.log('Staff:', staff); // Check what is logged here

  if (!staff) {
    return <div>No staff member data available. Please navigate from the staff list.</div>;
  }

  return (
    <div>
      <h1>{staff.title}</h1>
      {/* Render other staff details */}
    </div>
  );
};

export default StaffDetail;

Issues:
1.Undefined Staff Object: When navigating to the StaffDetail component, staff is undefined, even though it should be passed through the Link state.
2.Direct URL Navigation: I have confirmed that I’m not directly entering the URL in the address bar, which I understand would lead to state being undefined.
3.Logging the Location: I’ve logged the location object and found that location.state is null when I expect it to be populated with the staff object.

Error: Route “/[locale]” used headers().get(‘X-NEXT-INTL-LOCALE’). headers() should be awaited before using its value in Next.js with next-intl

I’m currently working with Next.js 15 and next-intl for i18n (internationalization) in my application. Everything seems to be working fine, but I am getting the following error when trying to access the locale in my layout:

Error: Route “/[locale]” used headers().get('X-NEXT-INTL-LOCALE'). headers() should be awaited before using its value.

Here is the layout where I use next-intl:

import { NextIntlClientProvider } from "next-intl";
import { headers } from "next/headers";
import { notFound } from "next/navigation";

export async function generateStaticParams() {
  return [{ locale: "en" }, { locale: "lt" }];
}

export default async function LocaleLayout({ children, params }) {
  const param = await params;
  const localeFromParams = param?.locale;

  const headerLocale = await headers().then((hdr) =>
    hdr.get("X-NEXT-INTL-LOCALE")
  );

  const locale = localeFromParams || headerLocale;

  if (!locale) {
    notFound();
  }

  let messages;
  try {
    messages = (await import(`../../messages/${locale}.json`)).default;
  } catch (error) {
    notFound();
  }

  return (
    <html lang={locale}>
      <body>
        <NextIntlClientProvider locale={locale} messages={messages}>
          {children}
        </NextIntlClientProvider>
      </body>
    </html>
  );
}

Steps I’ve taken to resolve the issue:

I am correctly awaiting params and headers() in my layout, but I still receive this error.
I’ve checked my middleware.js configuration, and it seems to be set up properly for next-intl to pass the locale correctly.
I even attempted to await headers() before accessing get(“X-NEXT-INTL-LOCALE”), as mentioned in the error, but the issue persists.

Error Details:

The error message suggests that headers() should be awaited, but I have done so already.
I’m using the next-intl package to handle translations dynamically based on the locale in the URL, but I keep getting the error when trying to fetch the locale from headers.

My request.js for fetching the translations:

import { getRequestConfig } from "next-intl/server";

export default getRequestConfig(async ({ locale }) => {
  if (!locale) {
    console.error("Locale is undefined in getRequestConfig.");
    throw new Error("Locale is undefined in getRequestConfig.");
  }

  try {
    const messages = await import(`../messages/${locale}.json`);
    console.log("Loaded messages for locale:", locale);
    return { messages: messages.default };
  } catch (error) {
    console.error(`Failed to load messages for locale: ${locale}`, error);
    throw new Error(`Failed to load messages for locale: ${locale}`);
  }
});

What I expect to happen:

The locale should be correctly retrieved from either the URL parameters (params) or the headers (X-NEXT-INTL-LOCALE), and the corresponding translation file should be loaded.

What I have tried:

Awaiting params and headers() properly.
Ensuring the translation files are correctly imported.
Trying both approaches (params.locale and headers().get(“X-NEXT-INTL-LOCALE”)), but the error persists.

Questions:

Why am I still getting the headers() error, even though I’m using await properly?
Is there anything I’m missing in the configuration, or is there a specific pattern I should be following with next-intl in Next.js 15?

Any guidance or suggestions would be greatly appreciated!

get dimensions of video twitch extension

I am developing a twitch extension that requires me to position items relative to the contents of the stream. For this i need to know the dimensions of the video in twitch, which I was trying to get from the html element. It seems that the actual video has some baked in padding as the container contains the video with some black padding around it. Is there a way to get the dimensions of the actual video either from the html or another way?

Edge label is getting overlapping in one another

const newEdge = {
    ...params,
    type: 'smoothstep',
    label: ``,
    animated: true,
    markerEnd: { type: "arrowclosed" },
    style: {
      stroke: color ? color : " #a6acaf",
    },
    labelStyle: {
      fontSize: "14px",
      fontWeight: "bold",
      borderRadius: "50%",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      textAlign: "center",
      lineHeight: "10px",
      color: "#fff",
      fill: "#fff",
    },
    labelShowBg: true,
    labelBgStyle: {
      backgroundColor: color,
      borderRadius: "50%",
      fill: color,
      width: "25px",
      height: "26px",
    },
    labelBgPadding: [6, 6],
    labelBgBorderRadius: 15,
  };

Using above code i am creating my edge and label with styles here problem is ,once i have two nodes and i am trying interconnect both and giving diferent edge label for both node edge connections but both are getting overlapped on one another and i am not able to see which is down the overlapped one.I have tried transform but its not working once edge is created its created as svg so the label wrapper is a element.

CODE REFERENCE :
transform: translate(-50%, -50%) translate(${labelX}px,${labelY}px), This is the basic style will be appended once label got added ,so the label will centered in the middle .

EXPECTED SOLUTION :
Randomize the edge label position or transform for all the edge which is getting created as new edge

React: “key” Prop Being Spread into JSX Using getInputProps from @conform-to/react

I am encountering an issue where React complains about a key prop being spread into a JSX element, even though I’m not explicitly passing it as part of my props.

Here’s the relevant code snippet:

<Input
  className="mb-[20px]"
  label="First Name"
  errorMessage={fields.firstName.errors?.at(0)}
  {...getInputProps(fields.firstName, { type: "text" })}
/>

The error message:

A props object containing a "key" prop is being spread into JSX:
  let props = {key: someKey, className: ..., label: ..., errorMessage: ..., required: ..., id: ..., name: ..., form: ..., type: ..., minLength: ...};
  <Input {...props} />
React keys must be passed directly to JSX without using spread:
  let props = {className: ..., label: ..., errorMessage: ..., required: ..., id: ..., name: ..., form: ..., type: ..., minLength: ...};
  <Input key={someKey} {...props} />

Conform documentation: https://conform.guide/api/react/getInputProps

I’m using NextJS15, React, Typescript.

How to render Candlestick Series above Area Series in Lightweight Charts?

I am trying to ensure that the Candlestick Series is rendered above the Area Series in a Lightweight Charts graph. However, changing the sequence of the code does not work and results in a blank graph.

Here’s the script I’m using to create the chart:

fetch('/data')
    .then((response) => response.json())  // Get the JSON data
    .then((data) => {
        // Create the chart instance
        const chart = LightweightCharts.createChart(document.getElementById('chartContainer'), {
            layout: {
                textColor: 'black',
                background: { type: 'solid', color: 'white' },
            },
        });
        const candlestickSeries = chart.addCandlestickSeries({
            upColor: '#26a69a',
            downColor: '#ef5350',
            borderVisible: false,
            wickUpColor: '#26a69a',
            wickDownColor: '#ef5350',
        });
        candlestickSeries.setData(data.candlestickSeries);
 // Risk Zone (Stop Loss area)
        const riskZoneSeries = chart.addAreaSeries({
            lineColor: 'transparent',  // No border for the block
            topColor: 'rgba(252, 215, 218, 0.7)',  // Transparent red
            bottomColor: 'rgba(252, 215, 218, 0.7)', // Same color as top for solid fill
        });


 riskZoneSeries.setData([
            { time: startTime, value: entrancePrice }, // Start of the area at Entrance Price
            { time: endTime, value: entrancePrice },   // End of the area at Entrance Price
            { time: endTime, value: stopLossLevel },   // End of the area at Stop Loss
            { time: startTime, value: stopLossLevel }, // Start of the area at Stop Loss
        ]);

I expected the candlestick chart to appear above the area chart, but currently, it doesn’t render as intended.
How can I control the rendering order of the series in Lightweight Charts?

Error in Firebase Deploy Due to ESLint Issues and Lint Command Execution Fails (ENOENT)

I’m facing a problem while deploying my Firebase project. After running the firebase deploy command from the root of my project, I encountered a significant number of ESLint errors and the deployment failed with the following error message:

Additionally, my ESLint output lists multiple problems such as:

Object Curly Spacing: There should be no space after ‘{‘ or There should be no space before ‘}’
Line Length: This line has a length of 208. Maximum allowed is 80
Indentation Issues: Expected indentation of X spaces but found Y
Trailing Comma: Missing trailing comma

Questions:

  1. Why is the lint command being invoked during deployment, and how can
    I bypass or fix this?
  2. How can I fix the ENOENT error related to
    %RESOURCE_DIR%?
  3. What’s the best way to address these linting issues
    across multiple files efficiently?
  4. Should I reconfigure Firebase or
    ESLint to handle this issue better?

Any insights or solutions would be greatly appreciated! Thank you!

enter image description here

enter image description here

Using PostMessage to Communicate Child and Main App in React

I have a problem communicating the “child app” and “main app” and vice versa.
I just couldn’t get any message from both of them

Parent App > ParentAppComponent

const ParentAppComponent = () => {
  const childOrigin = 'http://localhost:5173';
  const ref = useRef();

  function onReceivedMessage(event) {
    if (event.origin !== childOrigin) {
      return;
    }

    console.log(event, 'HEY EVENT');
  }

  useEffect(function () {
    window.addEventListener('message', onReceivedMessage);

    return function () {
      window.removeEventListener('message', onReceivedMessage);
    };
  });

  return (
    <div>
      <iframe ref={ref} src={childOrigin} title="Child App" />
    </div>
  );
};

export default ParentAppComponent;

Child App > ChildAppComponent

const ChildAppComponent = () => {
  const mainAppOrigin = 'http://localhost:3000';

  const sendMessage = () => {
    window.postMessage('Hello from Child App', mainAppOrigin);
  };

  return (
    <div>
      <button onClick={sendMessage}>Send Message</button>
    </div>
  );
};

export default ChildAppComponent;

What could cause this misalignment, and how can I fix it to ensure the headers align perfectly with the rows in the table?

I’m building a React application with styled-components, and I’m having trouble aligning my MarketHeader and TableContent components. They are both children of a parent container and use flexbox for layout, but the content in the header doesn’t align with the rows in the table.

I created a codesandbox with the snippets relevant of the code: https://codesandbox.io/p/sandbox/market-component-dwcfxm

If someone can take a quick look and help me with some CSS with the alignment of the values with the header labels (currency, bid, ask, etc.,)