Javascript how to return native string symbol iterator when string not include “!”?

I have meet some problem , i want to return native string symbol iterator when string not include “!”

Object.defineProperty(
    String.prototype,Symbol.iterator,
                {
    writable: true, configurable: true, enumerable: false,
    value: function iterator(){
   
    var i, inc, done = false,str=this

    return {
   
    next() {

    if((str).includes("!")){
      do custom iterator
    }else {
        return native string iterator
    }
     } };
    } }
    ); 

Any pepole can help , thanks!

How to reload a site that was previously opened in js

im trying to refresh a url that is opened until it is canceled by the user manually

This is the actual code that i used – Used for an exploit in most chrome blocking extensions that unblock a website after cancel. your text

<html>
<script>

let site = prompt("Site?")
let open_site = window.open(site)
while (true)  {
window.open_site.reload()
}

</script>
</html>

Using Node.js, fetching a webpage is different from on the browser

I am trying to use fetch on Node.js, to fetch the page: https://finance.yahoo.com/quote/META

I can see on the browser it is at a price of $443.29

Also if I use view-source:https://finance.yahoo.com/quote/META on the browser and set Disable JavaScript to ON on Google Chrome’s dev tool, I can see the following content:

data-field="regularMarketPrice" data-trend="none" data-pricehint="2"
data-value="443.29" active><span>443.29

However, if I do a fetch using Node.js, or even if I go to Chrome’s dev tool and the Network tab, and reload the page, and then right click on the first network resource, and right click and choose

Copy -> as fetch (Node.js)

I can get the equivalent of what Google Chrome used:

    fetch("https://finance.yahoo.com/quote/META", {
          headers: {
            accept:
              "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language":
              "en",
            "cache-control": "max-age=0",
            "sec-ch-ua":
              '"Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": '"macOS"',
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "same-origin",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1",
          },
          referrerPolicy: "no-referrer-when-downgrade",
          body: null,
          method: "GET",
          mode: "cors",
          credentials: "include",
        });

However, I tried to do a JS match, and cannot get the 443.29 string, but instead, keep on getting this:

Fz(36px) Mb(-4px) D(ib)" data-symbol="META" data-test="qsp-price" 
data-field="regularMarketPrice" data-trend="none" data-pricehint="2" 
value="511.9" active="">511.90

and $511.9 was the price as of 2, 3 days ago. What is the correct way to get the price (even if it is delayed 20 minutes or a couple of hours, but not for a couple of days).

The Node.js I am using is v20.10.0, which should be quite update.

P.S. to make it into a runnable program, the following can fetch the data and match the price:

const fetch = require("node-fetch");

fetch("https://finance.yahoo.com/quote/META", {
  headers: {
    accept:
      "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "accept-language": "en",
    "cache-control": "max-age=0",
    "sec-ch-ua":
      '"Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"macOS"',
    "sec-fetch-dest": "document",
    "sec-fetch-mode": "navigate",
    "sec-fetch-site": "same-origin",
    "sec-fetch-user": "?1",
    "upgrade-insecure-requests": "1",
  },
  referrerPolicy: "no-referrer-when-downgrade",
  body: null,
  method: "GET",
  mode: "cors",
  credentials: "include",
})
  .then((res) => res.text())
  .then((data) => console.log([...data.matchAll(/511..{30}/g)]));

and it will show the price match for 511. but not if I change the 511 to 443 — then it will not be able to match anything. (note that because the price change, so you may need to change to the prices later on, or you can change the last line to:

  .then((data) =>
    console.log([...data.matchAll(/36px.*regularMarketPrice.{80}/g)])
  );

instead.

Tring to build an autocomplete input for a weather desktop app

I am trying to build a weather app for a self-guided Vanilla JavaScript course. I have successfully fetched the code for the API from the accuWeather website, but I can’t figure out how to display it. I am trying to make it so that when the user types any letter onto the search bar, it’ll open a drop-down of some sort displaying cities that start with that letter. When I console.log it on the forecast.js file, I am able to get back those cities by applying this method:

data.forEach(city => console.log(`${city.AdministrativeArea.LocalizedName}, ${city.Country.LocalizedName}`))

and setting a random string-letter inside the function getAutoCities().

here is what I have so far:

forecast.js file (Here is where I fetch the information from the API):

    const key = 'P7USqIWPhyor91rmlvOTcRaMyMgwfrfrg'

//get Autocomplete List
const getAutoCities = async (search) => {
    const base = 'http://dataservice.accuweather.com/locations/v1/cities/autocomplete';
    const query = `?apikey=${key}&q=${search}`

    const response = await fetch(base + query);
    const data = await response.json();

    return data;
};

This top part is a separate JS file I made to fetch the API. The bottom one is my app code.

app.js (The code for the app):

const cityForm = document.querySelector('form');
const card = document.querySelector('.card');
const details = document.querySelector('.details');
const time = document.querySelector('.time');
const icon = document.querySelector('.icon img');
const inputField = document.querySelector('input');
const autofill = document.querySelector('.autocomplete')

const updateUI = (data) => {

    //destructure properties
    const {cityDets, weather} = data;
    

//update details template
    details.innerHTML = `
    <h5 class="my-3">${cityDets.EnglishName}</h5>
    <div class="my-3">${weather.WeatherText}</div>
    <div class="display-4 my-4">
        <span>${weather.Temperature.Imperial.Value}</span>
        <span>&deg;F</span>
    </div>
    `;


    //update day.night & icon images
    const iconSrc = `img/icons/${weather.WeatherIcon}.svg`;
    icon.setAttribute('src', iconSrc);

    let timeSrc = weather.IsDayTime ? 'img/day.svg' : 'img/night.svg';

    time.setAttribute('src', timeSrc);

    //remove the d-none if present
    if(card.classList.contains('d-none')) {
        card.classList.remove('d-none');
    }


}

const updateCity = async (city) => {

    const cityDets = await getCity(city);
    const weather = await getWeather(cityDets.Key);

return {cityDets, weather};

};


cityForm.addEventListener('submit', e => {
    e.preventDefault();

    //get city value
    const city = cityForm.city.value.trim();
    cityForm.reset();


    //update UI with new city
    updateCity(city)
     .then(data => updateUI(data))
     .catch(err => console.log(err));
});

Where and how would I insert the code to show the data I fetched from the api?

Why is JavaScript two-sided string literal interpolation not quadratic?

In JavaScript, why is this classic quadratic-append not O(n²)?

s = "";
for (i = 0; i < 1000000; i++) {
  s = `( ${s} )`
};
console.log(s.length)

It’s O(n) in both Firefox 124 and Chromium 123.

In Python, it’s O(n²) as expected:

s = ""
for i in range(50_000):  # increase by 2x, gets 4x slower
  s = f"( {s} )"
print(len(s))

What is this magic, how are browsers cheating here?
Is that behaviour guaranteed by the ECMAScript spec?

I wanted to get a array of objects in a flat sturcture for the parent it’s child and it’s grand child and it’s great grandchild and so on

I have an array of objects like below
[{Portfolio:”AMBAL”,
Level:1,
Immediate Parent:””},
{Portfolio:”AMBAL-PI”,
Level:2,
Immediate Parent:”AMBAL”},
{Portfolio:”AMBAL-FI”,
Level:2,
Immediate Parent:”AMBAL”},

{Portfolio:”2213AMBAL”,
Level:3,
Immediate Parent:”AMBAL-FI”},
{Portfolio:”2132AMBAL”,
Level:3,
Immediate Parent:”AMBAL-PI”}….]

I have just gave example of level 3 but it could may have more also….

Expected o/p

[{Portfolio:”AMBAL”,
Level:1,
Immediate Parent:””},

{Portfolio:”AMBAL-FI”,
Level:2,
Immediate Parent:”AMBAL”},

{Portfolio:”2213AMBAL”,
Level:3,
Immediate Parent:”AMBAL-FI”},

{Portfolio:”AMBAL-PI”,
Level:2,
Immediate Parent:”AMBAL”},

{Portfolio:”2132AMBAL”,
Level:3,
Immediate Parent:”AMBAL-PI”}

]
Return the above array of objects using javascript only

Why am I getting the error ‘Cannot read property ‘title’ of undefined’ after including a function in a useEffect hook?

I’m using a useEffect hook which includes a delete function in it. Before including the delete function in the useEffect hook my code was working fine and I was able to navigate between different object data without any worries. Since calling the function in the hook I get the error ‘Cannot read property ‘title’ of undefined’

I have tried to use a useCallBack hook incase the function variables change through user interaction and I’ve also included default values for the object, index for each object in the array and object properties in case some of these values were not accessible to the useEffect hook during the initial render. Both efforts still produce the same error. Here is the relevant code:

//Default Values
 //Note list index use state.
  const [index, setIndex] = useState(0);
  //List of notes use state.
  const [noteList, editNoteList] = useState([
    {
      title: 'First Note',
      text: 'This is my first note on the app :)',
      expiry: new Date(),
    },
    {
      title: 'Test 2',
      text: 'This is my first note on the app :)',
      expiry: new Date(),
    },
    {
      title: 'Test 3',
      text: 'This is my first note on the app :)',
      expiry: new Date(),
    },
  ]);


const Timer = () => {
  const [isDatePickerVisible, setDatePickerVisible] = useState(false);
  //Index use state.
  const { index, setIndex } = useContext(IndexContext);
  //List of notes use states.
  const { noteList, editNoteList } = useContext(NoteListContext);
  //Set inital value of noteList if undefined.
  const initialNote = noteList[index] || {};
  //Set initial expiryDate to current date if initialNote.expiry is undefined
  const initialExpiryDate = initialNote.expiry || new Date();
  const [expiryDate, setExpiryDate] = useState(initialExpiryDate);
  //Set other states dependent on noteList[index] conditionally. Set initial title to an empty string if initialNote.title is undefinedSet initial title to an empty string if initialNote.title is undefined
  const [title, setTitle] = useState(initialNote.title || '');
  const [content, setContent] = useState(initialNote.content || '');

//Delete function and useEffect hook.
  //Delete note function using useCallback.
  const deleteNote = useCallback(() => {
    const noteListToEdit = [...noteList];
    noteListToEdit.splice(index, 1);
    editNoteList(noteListToEdit);
    saveNotes(noteListToEdit);
  }, [index, noteList, editNoteList]);

  useEffect(() => {
    const calculateTimeUnits = (timeDifference) => {
      const seconds = Math.floor(timeDifference / 1000);
      setTimeUnits({
        days: Math.floor((seconds % (365 * 24 * 60 * 60)) / (24 * 60 * 60)),
        hours: Math.floor((seconds % (24 * 60 * 60)) / (60 * 60)),
        minutes: Math.floor((seconds % (60 * 60)) / 60),
        seconds: seconds % 60,
      });
    };

    const updateCountdown = () => {
      const currentDate = new Date().getTime();
      const expiryTime = expiryDate.getTime();
      const timeDifference = expiryTime - currentDate;

      if (timeDifference <= 0) {
        calculateTimeUnits(0);
        deleteNote();
        //navigation.navigate('Recent Notes');
      } else {
        calculateTimeUnits(timeDifference);
      }
    };

    updateCountdown();

    const interval = setInterval(updateCountdown, 1000);

    return () => clearInterval(interval);
  }, [expiryDate, deleteNote]);

Fetch works but http post doesn’t in Angular ts file, what am I doing wrong?

I have this fetch statement below that works fine in my .ts file.

const fileResult = await fetch(environment.stripeFileUrl, {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer ' + environment.stripePublishableKey
  },
  body: data,
});
const fileData = await fileResult.json();

But when I write it like this below I get a status 401, status Text Ok, but an error that says my API key is incorrect.
Am I plugging in the header incorrectly?

New code that doesn’t work

this.accountService.getStripeIdentityToken(data).subscribe(response => {
  if (response.error) {
    this.showError(response.error.message);
  } else {
    this.outputFile.emit({
      file: response.id,
      description: null
    });
  }
}, error => {
  console.log(error);
}).add(() => {
  this.loading(false);
});



getStripeIdentityToken(data: any) {
  let headers = new HttpHeaders();
  headers = headers.set('Authorization', `Bearer ${environment.stripePublishableKey}`);
  // I also tried below with same error about the incorrect API key
  // headers = headers.set('Authorization', `Bearer pk_test_fTr...BVLn9e6`);

  return this.http.post<any>(environment.stripeFileUrl, data, {
    headers
  });
}

Textarea + hidden div or content editable div to use the Rect API?

I am making a text editor and I need to detect where browsers create line breaks due to element’s width limits. I found that the Rect API can be used for this purpose but it’s not compatible with textarea since it is a replaced element.

I have come to a split: Do I go with a textarea + a hidden div or a content editable div?

Textarea + hidden div:

Pros:

  • Easier to maintain
  • I can simply replicate its content with a hidden div with the same styling to be able to use the Rect API

Content editable div

Pros:

  • No need to maintain two elements

Cons:

  • More complicated to maintain
    • Need to replace div tags created by the return key with br tags

SQLITE_BUSY: database is locked | Sequelize Node Javascript

router.post("/update-quiz", upload.single("file"), async (req, res) => {
    const transaction = await sequelize.transaction();

    try {
        const actions = {
            "Multiple Choice": async (questions, transaction) => {
                const data = await MultipleChoice.bulkCreate(questions, {transaction: transaction});
                return data.map(question => question.question_id);
            },
            "Identification": async (questions, transaction) => {
                const data = await Identification.bulkCreate(questions, {transaction: transaction});
                return data.map(question => question.question_id);
            },
            "True or False": async (questions, transaction) => {
                const data = await TrueOrFalse.bulkCreate(questions, {transaction: transaction});
                return data.map(question => question.question_id);
            }
        };

        const deleteActions = {
            "Multiple Choice": async (questions_id, transaction) => {
                await MultipleChoice.destroy({
                    where: {
                        question_id: {
                            [Op.or]: questions_id
                        }
                    }
                }, {transaction: transaction});
            },
            "Identification": async (questions_id, transaction) => {
                await Identification.destroy({
                    where: {
                        question_id: {
                            [Op.or]: questions_id
                        }
                    }
                }, {transaction: transaction});
            },
            "True or False": async (questions_id, transaction) => {
                await TrueOrFalse.destroy({
                    where: {
                        question_id: {
                            [Op.or]: questions_id
                        }
                    }
                }, {transaction: transaction});
            }
        };

        const quiz = JSON.parse(req.body.quiz);
        const questions = JSON.parse(req.body.questions);

        if (Object.keys(actions).includes(quiz.type)) {
            const validator = {
                "Multiple Choice": validateMultipleChoice,
                "Identification": validateIdentification,
                "True or False": validateTrueOrFalse
            };
            const validations = getValidations(questions, quiz, validator[quiz.type]);
            if (validations.every(v => v.isValid)) {
                const previousQuiz = await Quiz.findOne({where: {quiz_id: quiz.quiz_id}}, {transaction: transaction});
                await deleteActions[previousQuiz.type](previousQuiz.questions_id.split("|"), transaction);
                const newQuestions = await actions[quiz.type](questions, transaction);

                let fileName = "";

                if (!req.file) {
                    fileName = `${quizImagePath}/${createDateForFile()}.png`;
                    createImage(300, 200, fileName, 30, "quizzy-quest");
                } else {
                    fileName = `${quizImagePath}/${req.file.filename}`;
                }

                await Quiz.update(
                    {
                        name: quiz.name,
                        description: quiz.description,
                        topic: quiz.topic,
                        type: quiz.type,
                        visibility:quiz.visibility,
                        questions_id: newQuestions.join("|"),
                        image_path: fileName
                    },
                    {where: {quiz_id: quiz.quiz_id}},
                    {transaction: transaction}
                );

                await transaction.commit();
                return res.status(201).json({message: "Quiz successfully updated."});
            } else {
                return res.status(400).json(validations.filter(v => !v.isValid).map(v => v.message));
            }
        } else {
            return res.status(400).json(["Invalid quiz type"]);
        }
    } catch (error) {
        await transaction.rollback();
        return res.status(500).json({error: error.toString()});
    }
});

The route is about updating the quiz (sequelize model) then remove the previous questions
(sequelize model) and add the edited/updated questions. I add transaction for data integrity. I debug where the SQLITE_BUSY error come from and it is in the Quiz.update. Please explain to me what is happening here why I am getting that error, how could I handle this problem. Any help would be appreciated.

How to correctly display animated images of significant sizes on a website

I am developing a website where I need to display quite large images (around 1 MB each) as part of a parallax effect. Additionally, I want to use many significantly smaller images as particle effects, utilizing both and . While is a bit more challenging to implement, it offers better performance.

What is the most effective way to implement a significant number of images manipulated by code (e.g., parallax effects or changing positions relative to the mouse cursor)? Are there any libraries specifically suited to handle this issue?

Best practices for managing asynchronous operations in JavaScript to avoid callback hell [closed]

How can I efficiently handle asynchronous operations in JavaScript to avoid callback hell?

I’m currently working on a JavaScript project where I’m dealing with multiple asynchronous operations. However, I’m encountering callback hell, and my code is becoming increasingly difficult to manage. I’m looking for some guidance on how to handle asynchronous operations more efficiently to avoid this issue.

Specifically, I’m interested in learning about best practices or patterns that can help streamline my asynchronous code and prevent it from becoming overly nested with callbacks. Are there any design patterns, libraries, or techniques that are commonly used to address this problem?

I’ve explored using Promises and async/await, but I’m still struggling to refactor my code effectively. Any insights or examples demonstrating how to refactor asynchronous code to make it more manageable would be greatly appreciated.

Additionally, if there are any common pitfalls or mistakes to avoid when dealing with asynchronous operations in JavaScript, I’d love to learn about those as well.

After yarn link, locally started server crashes with the Failed to compile ../../email-editor/lib/cjs/email-editor.js:37:0 Module not found:

I have a repository named email-editor, and I’m trying to locally run my changes with email-editor in the designs project.

I’m using Windows OS and Git Bash as my terminal. When I run each repository separately locally, I don’t encounter any issues. However, when I use yarn link to pull local changes from one repository into the other, I’m unable to start the server. It fails with the following error:

Failed to compile ../../email-editor/lib/cjs/email-editor.js:37:0 Module not found: Can't resolve '../node_modules/style-inject/dist/style-inject.es.js'

What I Tried:
I followed a series of steps to integrate changes from the email-editor repository into the designs project:

Built the email-editor project using yarn build.
Navigated to the designs repository.
Used yarn link email-editor to create a symbolic link to the local email-editor package within designs.
Attempted to start the server in designs by running yarn qa.

Expected Outcome:
I expected the server in the designs project to start successfully after linking email-editor and applying its changes. Specifically, I anticipated that the changes from email-editor would seamlessly integrate into designs, allowing the server to run without issues.

Actual Result:
Unfortunately, the server startup (yarn qa) failed instead of starting successfully as expected. This outcome was unexpected and did not align with the anticipated result of a functional server running with the integrated changes from email-editor.

How to configure Socket.io in nextjs for production?

This is my server.js file

const { createServer } = require('http');
const next = require("next");
const { Server } = require("socket.io");

const dev = process.env.NODE_ENV !== "production";
const hostname = "https://quiet-mooncake-8ff89f.netlify.app/";
const port = 3000;
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev , hostname });
const handler = app.getRequestHandler();

app.prepare().then(() => {
  const httpServer = createServer(handler);

  const io = new Server(httpServer);
  /.../

});

This is my Component

"use client";

import { io } from "socket.io-client";

const socket = io();

I have deployed this project and whenever this Component renders it just shows loading and when i tried looking in the network tab in developers tool it shows a pattern of 2 API hitting again and again.
First is https://quiet-mooncake-8ff89f.netlify.app/socket.io/?EIO=4&transport=polling&t=OyShAVC
which has Parameters as ->

Request URL:
https://quiet-mooncake-8ff89f.netlify.app/socket.io/?EIO=4&transport=polling&t=OyShAVC
Request Method:GET

Status Code:308 Permanent Redirect

Remote Address:[2406:da18:b3d:e202::64]:443

Referrer Policy:strict-origin-when-cross-origin

and Response Parameters as ->

Age:0

Cache-Control:
no-cache

Cache-Status:
“Netlify Edge”; fwd=miss

Content-Type:
text/plain;charset=UTF-8

Date:
Fri, 26 Apr 2024 23:10:28 GMT

Location:
/socket.io?EIO=4&transport=polling&t=OyShAVC

Netlify-Vary:
header=x-nextjs-data,cookie=__prerender_bypass|__next_preview_data

Refresh:
0;url=/socket.io?EIO=4&transport=polling&t=OyShAVC

Server:
Netlify

Strict-Transport-Security:
max-age=31536000; includeSubDomains; preload

X-Content-Type-Options:
nosniff

X-Nf-Request-Id:
01HWEASA1Y24RXM1J3Z4W6W5MQ

And the other one is is just redirecting to 404 page not found
Please tell me what should i do..

I have tried chnaging the hardcoding the URL in my code but it is still nopt working

How to setup a nodejs project so client side node modules resolve in the browser

I have a nodejs and web project that has been getting more complex with time.

In the nodejs side I’m able to easily import and use node modules but on the web page size I’m getting errors when trying to use node modules.

My vscode project is setup like so:

/(nodejs pages here)
/public/(web pages here)
/public/myproject.js
/public/myproject.ts
/public/mypage.html
/public/lib/pixi/(pixijs files here) /* manually copied the files here */
/node_modules/(modules here)

I have a typescript file in the public directory and when I import it into my class the compiler has code complete. But when I load the page in the browser I get errors:

Uncaught TypeError: Failed to resolve module specifier “pixi.js”.
enter image description here

So, I manually moved the pixijs folder from node_modules/pixi.js to a directory in the public folder this seems to work but for some reason it’s not finding one of the classes.

import * as PIXI from 'pixi.js';
import { getCanvasBoundingBox } from "./lib/pixi/pixi.mjs";

Uncaught SyntaxError: The requested module './lib/pixi/pixi.mjs' does not provide an export named 'getCanvasBoundingBox' 

Does anyone know how to setup a nodejs project so that I can import node modules into my client side pages? I put all the web pages in /public because the guides online said that’s what you do but the browser doesn’t seem to like that as I’ve shown.

Here is part of my nodejs server page:

// html page template system
app.set("view-engine", "ejs");

// the default directory path for web pages 
app.use(express.static('public'));

// starts the server
app.listen(PORT, () => {
  var date = new Date();
  var time = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
  console.clear();
  console.log(`App running at http://localhost:${PORT} at ${time}`);
})

Ideally, what I want is a vscode project that fulfills these requirements:

  • has nodejs pages (ts pages)
  • has web pages (html, ts, css)
  • shares ts classes between nodejs and web ts/js)
  • both can import node modules
  • can use one tsconfig for both (or independent)
  • restarts the server on save
  • doesn’t restart the server on client side ts to js on save
  • i don’t want to use a web pack or whatever because i’m saving a file every 30 seconds (i don’t think i should have to)

All of the requests mention above work independently but it’s been extremely difficult to get them to all work together at the same time.