Should I deep copy when modifying nested object?

I recently started learning functional programming in Javascript, and one thing that’s valued is Immutability. One way to preserve immutability is to when we want to modify some object that we first create a copy and then modify that copy and return it, for example:

const person = {
    firstName: 'John',
    lastName: 'Smith',
}

const modifyFName = obj => {
    const objCopy = {...obj};
    objCopy.firstName = 'James';
    return objCopy;
}

console.log(modifyFName(person)) // {firstName: 'James', lastName: 'Smith'}
console.log(person) // {firstName: 'John', lastName: 'Smith'}

But if I want to modify some deeply nested object creating shallow copy like one above wouldn’t make much of a difference, for example:

const person = {
    firstName: 'John',
    lastName: 'Smith',
    parents: {
        mom: {
            firstName: 'Jennifer',
            lastName: "Swift"
        },
        dad: {
            firstName: 'Tom',
            lastName: 'Cartman'
        }
    }
}

const modifyDadName = obj => {
    const objCopy = {...obj};
    objCopy.parents.dad.firstName = 'Aurelion';
    return objCopy;
}

console.log(modifyDadName(person)) // {... dad: "Aurelion"}
console.log(person) // {... dad: "Aurelion"}

Both objects have changed. So I am wondering in this situation should I perhaps use deep copy, or maybe use some third-party Immutable data structures, or is there some other solution for this?

How to run several js files at once?

I’ve created simple tool that I would like to work daily to get new data everyday. I have few js files that I would like to run at once. Instead of manually typing in terminal:

node news.js 
node main.js
node weather.js

Can I automate it somehow to type one command and everything runs automatically when previous file finished task?

Thanks

ReactJS – Get Elements from iFrame on Hover

Hi I have a Reac/NextJS page which looks like this:

import Layout from "@/components/app/Layout";
import Sidebar from "@/components/app/Sidebar";

export default function SiteIndex() {
  return (
    <Layout>
      <div className="flex">
        <Sidebar />
        <div className="m-5">
            <iframe src="/page.htm"></iframe>
        </div>
      </div>

    </Layout>
  );
}

It has an iframe included inside it.

What I need is that when the user hovers over any HTML element in the iframe, I want to do the following:

  1. Highlight that element on the screen,
  2. Display the contents of that in the sidebar.
  3. Make that element editable. it doesn’t have to be saved. But just editable.

Is it possible to do? How can we achieve that using reactjs/javascript?

Not sure if this is relevant but say if the nextjs project is on example.com, the iframe is coming from test.example.com. I have access to both domains/projects.

How to fix error in my JS Project made by a Chrome Externsion Liner?

In my new Hangman App (making by course from Andrew J. Mead), the console tab has a error:

POST https://customer.iad-03.braze.com/api/v3/data/ net::ERR_BLOCKED_BY_CLIENT        liner-core.be.js:1

I dug down and clicked on the liner-core.be.js:1 link and it was a JS file. Here is the link because the code is too long to copy paste.

Mega Link

I tried to Ctrl + A delete the file but it came back. I don’t want to remove the extension as it is really good.

Thanks

Arrow function used in the built-in findIndex function

I am new to javascript and doing a nested find in an array as follow:

    var target = this.newRubric.categories
    .find((category) => category.name == this.indexTracker.selectedCategory)
    .criteria.find(
      (criterion) => criterion.name == this.indexTracker.selectedCriterion
    )
    .descriptors.findIndex(
      (descriptor) =>
        //Error here, works by removing the curly brackets 
        {descriptor.name == this.indexTracker.selectedDescriptor}
    );
  console.log(target);

It always returned -1 which is not found until I removed the curly braces, I know that if there was only one line of code the curly braces is not necessary, but why did adding it will cause an error in the findIndex method?

Simplified Calendar Generator using HTML and JavaScript

I currently have a code structure that automatically generates and outputs the current calendar status of your local timezone. But now, I want this to become even more simplified with and also user input dependent.

The logic here is:
(By utilizing an input form)
(This time, no year is needed and February is always 28 days)

  1. Ask the user for a month (1-12).
  2. Ask for the 1st day of the month (1-7) where 1 is Sunday and 7 is Saturday.
  3. If submit button is clicked, it will then generate the calendar.
    (where the 1st day of the month and its weekday is highlighted(in bold).

The output of this logic will look something like this:

enter image description here

Now, my problem with my own simplified version is that, it only works in identifying the month but the start day doesn’t work since it outputs the start day input then duplicates it in an odd way. Also, it won’t produce the succeeding days to complete the calendar structure. Clearly, I am a bit lost in simplifying the logic of my calendar generator.
Hoping you all could present me some guides and a certain flow of the right implementation for the simplified version that I am trying to attain.

Here’s my take on following the logic:

<html>
<head>
</head>

 <body>

<center>



<form action="#" method="post" onsubmit="return calcCalendar()">

<h2>Calendar Generator</h2>
   <label>Input month: (1-12)</label>
  <input id="monthNumm" type="number">
   </div> <br> <br>
   <div>
    <label>Start day of month: (1-7)</label>
   <input id="startNumm" type="number">
  </div> <br>
 
   <input type="submit" value="Submit">

  

    </form>



    <script language="javascript" type="text/javascript">

      function calcCalendar(){
    
      
    var day_of_week = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
    var month_of_year = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
    
    //  DECLARE AND INITIALIZE VARIABLES
    var Calendar = new Date();
    
    var year = Calendar.getFullYear();     // Returns year   
    var month = document.getElementById("monthNumm").value - 1;  // to ensure that 1 is considered as January, and so on..
    var today = document.getElementById("startNumm").value;     // Returns day (1-31)
    var weekday = document.getElementById("startNumm").value;    // Returns day (1-31)
   
    
    var DAYS_OF_WEEK = 7;    // "constant" for number of days in a week
    var DAYS_OF_MONTH = 31;    // "constant" for number of days in a month
    var cal;    // Used for printing
    
    Calendar.setDate(1);    // Start the calendar day at '1'
    Calendar.setMonth(month);    // Start the calendar month at now
    
    
    /* VARIABLES FOR FORMATTING
    NOTE: You can format the 'BORDER', 'BGCOLOR', 'CELLPADDING', 'BORDERCOLOR'
          tags to customize your caledanr's look. */
    
    var TR_start = '<TR>';
    var TR_end = '</TR>';
    var highlight_start = '<TD WIDTH="30"><TABLE CELLSPACING=0 BORDER=1 BGCOLOR=DEDEFF BORDERCOLOR=CCCCCC><TR><TD WIDTH=20><B><CENTER>';
    var highlight_end   = '</CENTER></TD></TR></TABLE></B>';
    var TD_start = '<TD WIDTH="30"><CENTER>';
    var TD_end = '</CENTER></TD>';
    
    /* BEGIN CODE FOR CALENDAR
    NOTE: You can format the 'BORDER', 'BGCOLOR', 'CELLPADDING', 'BORDERCOLOR'
    tags to customize your calendar's look.*/
    
    cal =  '<TABLE BORDER=1 CELLSPACING=0 CELLPADDING=0 BORDERCOLOR=BBBBBB><TR><TD>';
    cal += '<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=2>' + TR_start;
    cal += '<TD COLSPAN="' + DAYS_OF_WEEK + '" BGCOLOR="#EFEFEF"><CENTER><B>';
    cal += month_of_year[month]  + '   ' + year + '</B>' + TD_end + TR_end;
    cal += TR_start;
    
    //   DO NOT EDIT BELOW THIS POINT  //
    
    // LOOPS FOR EACH DAY OF WEEK
    for(index=0; index < DAYS_OF_WEEK; index++)
    {
    
    // BOLD TODAY'S DAY OF WEEK
    if(weekday == index)
    cal += TD_start + '<B>' + day_of_week[index] + '</B>' + TD_end;
    
    // PRINTS DAY
    else
    cal += TD_start + day_of_week[index] + TD_end;
    }
    
    cal += TD_end + TR_end;
    cal += TR_start;
    
    // FILL IN BLANK GAPS UNTIL TODAY'S DAY/////////////////////////////////////
    for(index=0; index < Calendar.getDay(); index++) 
    cal += TD_start + '  ' + TD_end;
    
    // LOOPS FOR EACH DAY IN CALENDAR
    for(index=0; index < DAYS_OF_MONTH; index++)
    {
    if( Calendar.getDate() > index )
    {
      // RETURNS THE NEXT DAY TO PRINT
      week_day =Calendar.getDay();
    
      // START NEW ROW FOR FIRST DAY OF WEEK
      if(week_day == 0)
      cal += TR_start;
    
      if(week_day != DAYS_OF_WEEK)
      {
    
      // SET VARIABLE INSIDE LOOP FOR INCREMENTING PURPOSES
      var day  = Calendar.getDate();
    
      // HIGHLIGHT TODAY'S DATE
      if( today==Calendar.getDate() )
      cal += highlight_start + day + highlight_end + TD_end;
    
      // PRINTS DAY
      else
      cal += TD_start + day + TD_end;
      }
    
      // END ROW FOR LAST DAY OF WEEK
      if(week_day == DAYS_OF_WEEK)
      cal += TR_end;
      }
    
      // INCREMENTS UNTIL END OF THE MONTH
      Calendar.setDate(Calendar.getDate()+1);
    
    }// end for loop
    
    cal += '</TD></TR></TABLE></TABLE>';
    
    //  PRINT CALENDAR
    document.write(cal);
     
    
    }
      
    
    //  End -->
    </script>



   </center>
   <br/><div style="clear:both"></div>


  </body>
  </html>

Here’s the output of it:

Output of my version

Now, here’s my previous version (the one that automatically generates the current calendar of your current timezone):

    <HTML>
   <head>
  </head>
  <body>
  <center>
  <script language="javascript" type="text/javascript">
  var day_of_week = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
  var month_of_year = new Array('January','February','March','April','May','June','July','August','September','October','November','December');

//  DECLARE AND INITIALIZE VARIABLES
var Calendar = new Date();

var year = Calendar.getFullYear();     // Returns year
var month = Calendar.getMonth();    // Returns month (0-11)
var today = Calendar.getDate();    // Returns day (1-31)
var weekday = Calendar.getDay();    // Returns day (1-31)

var DAYS_OF_WEEK = 7;    // "constant" for number of days in a week
var DAYS_OF_MONTH = 31;    // "constant" for number of days in a month
var cal;    // Used for printing

Calendar.setDate(1);    // Start the calendar day at '1'
Calendar.setMonth(month);    // Start the calendar month at now


    /* VARIABLES FOR FORMATTING
    NOTE: You can format the 'BORDER', 'BGCOLOR', 'CELLPADDING', 'BORDERCOLOR'
                tags to customize your caledanr's look. */

var TR_start = '<TR>';
var TR_end = '</TR>';
var highlight_start = '<TD WIDTH="30"><TABLE CELLSPACING=0 BORDER=1 BGCOLOR=DEDEFF BORDERCOLOR=CCCCCC><TR><TD WIDTH=20><B><CENTER>';
var highlight_end   = '</CENTER></TD></TR></TABLE></B>';
var TD_start = '<TD WIDTH="30"><CENTER>';
var TD_end = '</CENTER></TD>';

            /* BEGIN CODE FOR CALENDAR
        NOTE: You can format the 'BORDER', 'BGCOLOR', 'CELLPADDING', 'BORDERCOLOR'
            tags to customize your calendar's look.*/

cal =  '<TABLE BORDER=1 CELLSPACING=0 CELLPADDING=0 BORDERCOLOR=BBBBBB><TR><TD>';
cal += '<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=2>' + TR_start;
cal += '<TD COLSPAN="' + DAYS_OF_WEEK + '" BGCOLOR="#EFEFEF"><CENTER><B>';
cal += month_of_year[month]  + '   ' + year + '</B>' + TD_end + TR_end;
cal += TR_start;

//   DO NOT EDIT BELOW THIS POINT  //

// LOOPS FOR EACH DAY OF WEEK
for(index=0; index < DAYS_OF_WEEK; index++)
{

// BOLD TODAY'S DAY OF WEEK
if(weekday == index)
cal += TD_start + '<B>' + day_of_week[index] + '</B>' + TD_end;

// PRINTS DAY
else
cal += TD_start + day_of_week[index] + TD_end;
}

cal += TD_end + TR_end;
cal += TR_start;

// FILL IN BLANK GAPS UNTIL TODAY'S DAY
for(index=0; index < Calendar.getDay(); index++)
cal += TD_start + '  ' + TD_end;

// LOOPS FOR EACH DAY IN CALENDAR
for(index=0; index < DAYS_OF_MONTH; index++)
{
if( Calendar.getDate() > index )
{
// RETURNS THE NEXT DAY TO PRINT
week_day =Calendar.getDay();

   // START NEW ROW FOR FIRST DAY OF WEEK
if(week_day == 0)
 cal += TR_start;

 if(week_day != DAYS_OF_WEEK)
{

   // SET VARIABLE INSIDE LOOP FOR INCREMENTING PURPOSES
    var day  = Calendar.getDate();

 // HIGHLIGHT TODAY'S DATE
 if( today==Calendar.getDate() )
 cal += highlight_start + day + highlight_end + TD_end;

    // PRINTS DAY
 else
  cal += TD_start + day + TD_end;
}

   // END ROW FOR LAST DAY OF WEEK
    if(week_day == DAYS_OF_WEEK)
    cal += TR_end;
    }

    // INCREMENTS UNTIL END OF THE MONTH
   Calendar.setDate(Calendar.getDate()+1);

   }// end for loop

    cal += '</TD></TR></TABLE></TABLE>';

   //  PRINT CALENDAR
    document.write(cal);

 //  End -->
  </script>
  </center>
  <br/><div style="clear:both"></div>
  </body>
   </html>

and here is its output:

enter image description here

Hoping for your responses as this would help me a lot! Thank you very much!!!

How to turn object literal into a list of objects in Nextjs?

I have the follow assets stored in my public/testfiles folder:

const cycleImages = {
        1:'/testfiles/0090.jpg',
        2:'/testfiles/0091.jpg',
        3:'/testfiles/0092.jpg',
        4:'/testfiles/0093.jpg',
        5:'/testfiles/0094.jpg',
        6:'/testfiles/0095.jpg',
        7:'/testfiles/0096.jpg',
        8:'/testfiles/0097.jpg',
        9:'/testfiles/0098.jpg',
        10:'/testfiles/0099.jpg',
        11:'/testfiles/0100.jpg',
        12:'/testfiles/0101.jpg',
        13:'/testfiles/0102.jpg',
        14:'/testfiles/0103.jpg',
        15:'/testfiles/0104.jpg',
        16:'/testfiles/0105.jpg',
        17:'/testfiles/0106.jpg',
        18:'/testfiles/0107.jpg',
        19:'/testfiles/0108.jpg',
        20:'/testfiles/0109.jpg',
    }

I have used this to test some jsx logic but now I am ready to extend it to the rest of my pages. But before I do, I have thought about whether there is an efficient way to grab the assets from the public folder without manually typing everything as object literal.

I have used fs.readdir in getStaticProps but when I passed the props, it became undefined.

import { promises as fs } from 'fs'
import path from 'path'
//...
export async function getServerSideProps() {
    const FOLDER_NAME = "testfiles"
    const DIRECTORY = path.join(process.cwd(), "public", FOLDER_NAME)

    const posts = fs.readdirSync(DIRECTORY).filter(post => fs.lstatSync(path+post).isFile())

    return {
      props: {
        posts: await Promise.all(posts),
      },
    }
  }

Is there any way to access the files in the public folder in getStaticProps without resulting in an undefined?

How can I upload files using multer without knowing the fieldname

Can someone help me…I am new on multer and I don’t know how to upload files based on their key or fieldname

So these are my data…

    const items = {
      1: [], // array of files
      2: [], // array of files
      ...
    }

The problem is I don’t know what should I pass on multer upload.fields() because that data could have 1 or more items.

Thank You!

PS. I hope you guys understand what I’m saying :3

When I am trying to return a function I am getting a typescript error

I am creating a custom hook using typescript when I am trying to return the function name I am getting an error which is Type 'readonly [(email: string, password: string, name: string, history: any) => Promise<void>]' is not assignable to type 'ReactElement<any, any>'

I am getting an error here return [RegisterUser] as const

Here is my code.

const UseFirebase: React.FunctionComponent<IUseFirebaseProps> = (props: React.PropsWithChildren<IUseFirebaseProps>, context?: any): React.ReactElement<any, any> | null => {
    const [user, setUser] = useState({})
    const [error, setError] = useState('')
    const [admin, setAdmin] = useState(false)
    const [isLoading, setIsLoading] = useState(true)
    const auth = getAuth()


    // REGISTER WITH EMAIL AND PASSWORD
    const RegisterUser  = async (email: string, password: string, name: string, history: any)  => {
        setIsLoading(true)
        const userCredential = await createUserWithEmailAndPassword(auth, email, password)

        const newUser = {
            email,
            displayName: name
        };

        setUser(newUser);
        setError('')

        // Pass userCredential.user instead of auth.currentUser
        updateProfile(userCredential.user, {
            displayName: name
        }).then(() => { }).catch((error) => { });
        history.replace('/');
    }

    return [RegisterUser] as const

};

Can anyone help me, please? How can I solve the error.

Is there a way to open multiple tabs simultaneously on Playwright or Puppeteer to complete the same tasks?

I just started coding, and I was wondering if there was a way to open multiple tabs concurrently with one another. Currently, my code goes something like this:

const puppeteer = require("puppeteer");

const rand_url = "https://www.google.com";

async function initBrowser() {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();
  await page.goto(rand_url);
  await page.setViewport({
    width: 1200,
    height: 800,
  });

  return page;
}

async function login(page) {
  await page.goto("https://www.google.com");
  await page.waitFor(100);
  await page.type("input[id ='user_login'", "xxx");
  await page.waitFor(100);
  await page.type("input[id ='user_password'", "xxx");
}

this is not my exact code, replaced with different aliases, but you get the idea. I was wondering if there was anyone out there that knows the code that allows this same exact browser to be opened on multiple instances, replacing the respective login info only. Of course, it would be great to prevent my IP from getting banned too, so if there was a way to apply proxies to each respective “browser”/ instance, that would be perfect.

Lastly, I would like to know whether or not playwright or puppeteer is superior in the way they can handle these multiple instances. I don’t even know if this is a possibility, but please enlighten me. I want to learn more.

Change object parameter by useState() in ReactJS

So I’m trying to change an object parameter that is being called by .map inside a curly braces. Here is the code:

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

function App() {
  const [news, setNews] = useState([])
  const [searchQuery, setSearchQuery] = useState('city')

  const getNews = () => {
    fetch('https://api.randomuser.me/?nat=USA&results=5')
      .then(result => result.json())
      .then(data => setNews(data.results))
      .then(error => console.log(error))
  }

  const handSearch = (e) => {
    setSearchQuery(e.target.value)
  }

  //the [] at the end is enabled to request data only onces
  useEffect(() => {
    getNews()
  }, [searchQuery])
  
  return (
    <div>
      <form>
        <input onChange={handSearch}></input>
      </form>
      <p><b>Available Input: </b>city, state, country, postcode</p>
      <hr/>
      {
        news.map((value, index) => (
          <p key={index}>{`value.location.${searchQuery}`}</p>
        ))
      }
      <p>{searchQuery}</p>
    </div>
  );
}

export default App;

But it doesn’t work, it only return a string. I’ve tried to :

  1. Remove the Apostrophe ``
  2. Change the curly braces to another brackets []
  3. Make a const outside return() just for value.location.${searchQuery} and put it back to the curly braces
  4. Some other small changes I kinda forgot

How to complete an object parameter by ${}?

Any help would be appreciated, thanks before!

Import JS and CSS files into the JSP file, and the browser console prompts 404

I imported JS and CSS files in the head part of the JSP file. However, some JS and CSS files prompt 404 errors. My < head > section is as follows:
enter image description here

The prompt in the browser console is as follows
enter image description here

It can be seen that the “/ Editor” directory is missing in the prompted error
But when I modify other JS and CSS paths, the same error will be prompted

enter image description here

enter image description here

These files are in the “editor” directory. I have also tried to restart idea. Clearing the browser cache and restarting the computer have no effect. Hope to get an answer

Javascript function not working without return

When i use return at the and of function it renders as i want but if i dont use return it dont render.

const controlNext = function () {
  if (model.state.counterData.type === "work") {
    model.state.counterData.time = 300; //changes time data
    model.state.counterData.type = "timeout"; //changes time type
    renderClock(); //changes time data as min:sec and renders it
    clock.renderStatus("timeout"); //renders time type
    if (model.state.workData.currentWorkNum === -1) {
      return;
    } //if there is no work in query returns
    model.state.workData.works[model.state.workData.currentWorkNum].repeat--; //if there is work in query it gets one number down
    work.renderToList(model.state.workData.works); //renders works
    return; //if i dont use this return it dont render time data and renderstatus
  }
};

typescript extend new property without modifying existing type

I have this code

type VehicleDetails = {made: string}

function doSomethingWithVehicleDetails (details: VehicleDetails) { //what to add here for newProperty?
  console.log(details);
}

doSomethingWithVehicleDetails({ made: '123', newProperty: true })

https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/FDAuE8AcFMAIDVoAsCWBjANtAItUBDFDAZ1gF5YBvAW3wBNoAuWY0AJxQDsBzAXxABmAV05pQKAPadYdCQGUJ1PKh4B1FKCSJUmHHkIlYACgYEixZtvRZcZkgEoqsAPTOA7knyhYoCbHp0sEjQbHACEmywnNBuAApsEjBsEAD8wLCwaFLEElgAdBgS3Cb65vYA3MD8wLIKSppc3OqaVrq2BsRGlLC0DMwA5ACMAEwAzP0ANFEx8YkhEMzsQnC89kA

without modifying type VehicleDetails = {made: string}, how can I add newProperty in doSomethingWithVehicleDetails argument to fix the error?