JS generate subset of array with given number and slide count

I’m working on creating customized slider in reactJS for which I’m creating a function to generated expected output and this functions takes sliderItems(holds array list), slider count(variable name ‘spliceCount’) and with how many items it should slide(variable name ‘slideBy’).

let say I have a function which takes the three attributes like array, splice-count and slideBy and return me the subsets of array based on splice-count and slideby.
As of now with below function I’m able to generate the output as shown in below snippet.

const list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'];
const spliceCount = 3;
const slideBy = 2;
function getSusetofArray(array, splice, slide) {
  const arrayList = [...array];
  const subsetList = [];
   while(arrayList > 0) {
    subsetList.push(arrayList.splice(0, splice));
  }
  return subsetList;
}
console.log(getSusetofArray(list, spliceCount, slideBy));
// current output with above function
[['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I'], ['J', 'K']]

However, the expect out with the help of spliceCount and slideBy is needs to be like below one

expected output = [['A', 'B', 'C'], ['C', 'D', 'E'], ['E', 'F', 'G'], ['G', 'H', 'I'], ['I', 'J', 'K'], ['K']]

How to display the fetched data from the api on svelte?

first time i’m trying to write an app on svelte, i wrote the function to get the data from api and destructured the data to get only what i need. But i don’t get how to render it?

the function looks like this:

<script>
    async function getCurrencies() {
    const response = await fetch(BASE_URL);
    const data = await response.json();
    console.log(data);
    const { conversion_rates } = data;
    console.log(conversion_rates);
  }

getCurrencies();
</script>

and the element where i should render the information looks like this:

<div class="currency-input">
  <input type="number" min="0" /> // exchange rate should be displayed
  <select>
    <option value="USD">USD</option> // now it's hardcoded but i need to display the list of currencies from the API
  </select>
</div>

the response that i see on my console it’s an object with all the currencies like this:

{ USD: 1, EUR: 0.90, ... }

Someone can give some advice how to do it? I’m a little confused,

custom email contetent how to do it?

i need help because i want the stuff that i(someone) put inserted to the div “orderinfo” to be read and sent with emailjs with the mail
i need help

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Good Food</title>
    <link rel="stylesheet" href="styl.css">
    <link rel="script" href="zamow.js">
    <script type="text/javascript"
      src="https://cdn.jsdelivr.net/npm/@emailjs/browser@3/dist/email.min.js">
</script>
<script type="text/javascript">
   (function(){
      emailjs.init("k4PLn-odXcBlho7D8");
   })();
</script>

<script type="text/javascript"
       src="https://cdn.jsdelivr.net/npm/@emailjs/browser@3/dist/email.min.js">
</script>
<script type="text/javascript">
  (function () {
     emailjs.init("k4PLn-odXcBlho7D8");
  })();
</script>
<script>
  var templateParams = {
    from_name: 'order',
    message: 'details'
  };

  emailjs.send('service_1kb880o', 'template_hrbsaqs', templateParams) 
    .then(function (response) {
      console.log('SUCCESS!', response.status, response.text);
    }, function (error) {
      console.log('FAILED...', error);
    });

    
</script>



</head>
<body>
    <div class="gora">
    <div class="logo"><img  class="logoinazwa"    src="img/burger-line-64 (1).webp" alt="burger logo"></div>
    <div class="nazwa">Good Food <br> Best Catering</div>  

        <div class="ordercontainer">

            <div class="orderinfo" contenteditable="true">
                <p class="p">Addres line 1</p>
            </div>


            <div class="orderinfo" contenteditable="true">
                <p class="p">Addres line 2</p>
            </div>

            <div class="orderinfo" contenteditable="true">
                <p class="p">What time do you wish your food to be delivered?</p>
            </div>


            <div class="orderinfo" contenteditable="true">
                <p class="p">Additional requests</p>
            </div>

            <div class="button2"><p class="p2">Order Now</p>     </div>




        </div>


    
</div>
</body>

<footer class="footer"> Contact <br> Phone number +48 123 123 132 <br> E-mail [email protected] <br> Secondary e-mail [email protected]</footer>
</html>

javascript

var templateParams = {
    name: 'order',
    notes: 'next delivery'
  };
  emailjs.send('service_1kb880o', 'template_hrbsaqs', templateParams) 
    .then(function (response) {
      console.log('SUCCESS!', response.status, response.text);
    }, function (error) {
      console.log('FAILED...', error);
    });

    
     var orderinf = document.getElementsByClassName("orderinfo").addEventListener("click", displayDate);
    element.addEventListener("click", function(){ 
        
        var templateParams = {
            name: 'order',
            notes: 'details'
          };

          emailjs.send('service_1kb880o', 'template_hrbsaqs', templateParams ,) 
            .then(function (response) {
              console.log('SUCCESS!', response.status, response.text);
            }, function (error) {
              console.log('FAILED...', error);
            });
            var text=document.getElementsByClassName("orderinfo")
            print(text)
        
        ; });

im expecting it to read the div and send its content with the mail

I NEED HELP
(i know my code is messed up its my 2nd month of learning)
[ITS IN EMAILJS]

Why the fonts of my project are applied in Development Stage, but not in Production, project made in NextJS

I’m making a test product and I’ve already finished the ui with the surprise that when I deploy it to production it doesn’t have Google Fonts applied, it’s worth emphasizing that I’m using the import method for the fonts, I share the project’s repository image without fontsimage with fonts

git repo:https://github.com/Thewoker/NextJs/tree/main/gym-ecommerce

I didn’t really try many alternatives, right now I’m trying to implement the fonts no longer by importing from Google Fonts but from a local file with the fonts already downloaded

Why my terminal got stuck when I try to install ElectronJS from npm

So I am a javascript developer. I basically build web application with javascript using fontend library like react and backend framework linke express. but I wanted to try new things something like desktop development. then I stumble upon electron.js .So I thought “Why not? I know javascript fair enough. let’s try it.” then the first thing I did try to install the electron (like a normal person) following a decent tutorial. but somehow I couldn’t install the library at all. its just stuck on the last line for hours. here is my terminal activits..

PS E:studyElectronJSimage_resizer> npm i electron
npm WARN deprecated [email protected]: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
npm WARN deprecated [email protected]: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)
npm WARN deprecated [email protected]: core-js@<3.23.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Some versions have web compatibility issues. Please, upgrade your dependencies to the actual version of core-js.
[##################]  reify:core-js: WARN deprecated [email protected]: core-js@<3.23.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature 

I just tried to install a js library man..

React Router V6 Setup

I am working on a small e-commerce app using React.js.
While setting app the router v6, nothing is rendering. There should be a mistake in the configuring the router even in App.js or Index.js. here is a snapchot from the index.js code

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </>
);

reportWebVitals();

App.js

import React from 'react';
import Cart from './pages/Cart';
import Home from './pages/Home';
import ProductDetails from './pages/ProductDetails';
import {
  RouterProvider,
  Route,
  createBrowserRouter,
  createRoutesFromElements,
  Link
} from 'react-router-dom';

const Root = () => {
  return (
    <>
      <Link to="/">Home</Link>
    </>
  );
};

const appRouter = createBrowserRouter(
  createRoutesFromElements(
    <Route path="/" element={<Root />}>
      <Route path="home" element={<Home />} />
      <Route path="cart" element={<Cart />} />
      <Route path="product-details" element={<ProductDetails />} />
    </Route>
  )
)

function App() {
  return <RouterProvider router={appRouter} />;
}

export default App;

Please let me know if I am missing any import in index.js or if there is any mistake in App.js.

I tried online resources, tried to import createBrowserRouter and other but it did not work.

how can i get the data without that promise wrapper [duplicate]

when i write this code:

name: async function() {
        let ranNumber = ran();
        try {
            let response = await fetch('data/names.json');
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            let data = await response.json();
            let d = data[ranNumber];
            return d
        } catch (error) {
            console.error('There was a problem fetching the data:', error);
            return null;
        }
    },

i wanna the user of my lib just write nameOFLib.name() and get the data without do promise then etc

when i do nameOFLib.name() on console log it give me that :

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: "Mark"

and i just need the PromiseResult

Axios Promise.allSettled doesn’t work in parallel in Chrome

I have this parallel request mechanism in a ReactJS project. I followed the online sources while implementing this. I gather the promises in an array than feed it to allSettled then collect the result.

let promises = [];

for (const [_, url] of urls) {
    promises.push(axios.get(`https://url`, {
        timeout: 5000,
        signal: AbortSignal.timeout(5000), //Aborts request after 5 seconds
    }));
}

const result = await Promise.allSettled(promises)

My problem is that, in firefox this executes perfectly. However in Chrome, all the requests happen one by one(not parallel), so it is very slow and eventually timeout because of the 5 second limit I’ve put in.

Another interesting this is, if I open network tab and select “disable cache”, in Chrome, there requests happen in parallel and work the way they are supposed to.

What could be the reason for this?

axios version: 1.4.0

Node version: 18.2

How can I not have the addEventListener() functions run automatically when I run the project? [duplicate]

I have a small project I run using Live Server on VSCode. In this project I enter an email and password into fields. When I press save I want to store the values into localStorage, and clear the localStorage when I press clear.
But it seems that the addEventListener() runs automatically.

How do I get it to where the functions only run when I press the Save and Clear buttons?

Javascript

var email = document.getElementById('email');
var password = document.getElementById('password');

function save(email, password){
  try{
    localStorage.setItem("email", JSON.stringify(email) )
    localStorage.setItem("password", JSON.stringify(password) )
  }
  catch (err){
    console.log(err)
  }
  console.log(localStorage.getItem("email"));
  console.log(localStorage.getItem("password"));
}

function cancel(){
  localStorage.clear()
  console.log("Cancel Clicked")
}

document.getElementById("savebutton").addEventListener('click', save(email, password));
document.getElementById("cancelbutton").addEventListener('click',cancel());

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Local Storage App</title>
  </head>
  <body>
    <div>
      <h2>Local Storage Practice Example</h2>
      <div id="inputs">
        <div id="inputflex">
          <label>Email</label>
          <input type="email" id="email" />
        </div>
        <div id="inputflex">
          <label>Password</label>
          <input type="password" id="password" />
        </div>
      </div>
      <div>
        <button id="savebutton">Save</button>
        <button id="cancelbutton">Clear</button>
      </div>
    </div>
    <script src="/main.js"></script>
  </body>
</html>

Image of project.
The bottom shows the logs. It runs each time I start the project or refresh. I want the code to run only when I click save or clear buttons.

How do i edit the codepen FlipDown.js Countdown?

I found this countdown clock in CodePen, but I need to edit it, I need to set the final date to May 30, 2024. ¿Does anybody know how to set up the final date?

document.addEventListener('DOMContentLoaded', () => {

  // Unix timestamp (in seconds) to count down to
  var twoDaysFromNow = (new Date().getTime() / 1000) + (86400 * 2) + 1;

  // Set up FlipDown
  var flipdown = new FlipDown(twoDaysFromNow)

    // Start the countdown
    .start()

    // Do something when the countdown ends
    .ifEnded(() => {
      console.log('The countdown has ended!');
    });

  // Toggle theme
  var interval = setInterval(() => {
    let body = document.body;
    body.classList.toggle('light-theme');
    body.querySelector('#flipdown').classList.toggle('flipdown__theme-dark');
    body.querySelector('#flipdown').classList.toggle('flipdown__theme-light');
  }, 5000);
  
  var ver = document.getElementById('ver');
  ver.innerHTML = flipdown.version;
});

Or anybody can tell me where ¿I can find a flip countdown easy to set up?

THANKS

Why is encodeURI() replacing { with a load of UTF8? [closed]

I am trying to encode a string like BNg{​​L3 using encodeURI() but the result I get is this:

BNg%7B%E2%80%8B%E2%80%8BL3

Of course, I would like BNg%7BL3

I found that the sequence %E2%80%8B is ZERO WIDTH SPACE but it’s not in the provided string (I get the string from a query’s body, this problem shows up server-side). What does cause this behaviour? And more importantly, how do I get what I want?

Play only one audio at once

I have aa list of podcast links using the audio tag, they all play when I click on the play button but i want the first to pause when i play another

<div class="podcast-container">
    <audio controls src="https://assets.mixkit.co/music/preview/mixkit-tech-house-vibes-130.mp3"></audio>
    <audio controls src="https://assets.mixkit.co/music/preview/mixkit-hazy-after-hours-132.mp3"></audio>
    <audio controls src="https://assets.mixkit.co/music/preview/mixkit-tech-house-vibes-130.mp3"></audio>
</div>

I tried the below code to pause the audio but then it doesn’t play at all. Please help

  const tracks = Array.from(document.querySelectorAll('audio'));
   tracks.forEach(function (track) {
      track.addEventListener('play', (event) => {
         tracks.forEach(function (track) {
             track.pause();
         })
      })
   })

Is there a way to catch SyntaxError[s] thrown by the browser?

I have an angular app that introduced a negative lookbehind regex and broke compatabiliity with safari 15.6. We want to still support that version and have reverted to using compatible regex that it likes however this question is more about the code that throws the SyntaxError and how if possible can the I catch the error and then handle appropriately instead of serving the white screen of death.

Known things;

  • Non V8 browsers such as Safari don’t support them (lookbehind regex)
  • The immediate fix is to downgrade to tolerable regex syntax
  • I’ve successfully created the script tags in vanillaJS such that I could attach eventHandlers to each script. However the SyntaxError being thrown doesn’t trigger the errorHandler.0_o

Primary question:

  • Is the SyntaxError thrown by safari 15.6 in this case catchable? If so from where?
  • What code is parsing the regex and throwing an error if its not supported?

How to aggregate JSON data as expected?

I have response text from API as below, I want aggreate them to new format response. But it is quite difficult, please help me (using Javascript)

Response from API:

[
  {
    sumTime: "2024-04-25 12:00:00",
    equipParaName: "P1",
    sumValue: 5
  },
  {
    sumTime: "2024-04-25 05:00:00",
    equipParaName: "P2",
    sumValue: 10,
  },
  {
    sumTime: "2024-04-25 09:00:00",
    equipParaName: "P1",
    sumValue: 8
  },
  {
    sumTime: "2024-04-25 08:00:00",
    equipParaName: "P2",
    sumValue: 3,
  },
  {
    sumTime: "2024-04-25 08:00:00",
    equipParaName: "P3",
    sumValue: 12,
  }
]

Conditions:

  • With same sumTime, the equipParaName can not be duplicated

  • If have 3 unique equipParaName, the expecting result has maximum 3 attributes belongs to them in one object

  • Same equipParaName in result list must order by sumTime ASC

    equipParaName: P1, sumTime: 2024-04-25 12:00:00, sumValue: 5
    
    equipParaName: P1, sumTime: 2024-04-25 09:00:00, sumValue: 8
    
    ==> The sumTime 2024-04-25 09:00:00 should be added to 1st object and sumTime: 2024-04-25 12:00:00 added to 2nd object in result list
    

Expect:

[
  {
    index: 1,
    P1: 8,
    P1_sumTime: "2024-04-25 09:00:00",
    P2: 10,
    P2_sumTime: "2024-04-25 05:00:00",
    P3: 12,
    P3_sumTime: "2024-04-25 07:00:00"
  },
  {
    index: 2,
    P1: 5,
    P1_sumTime: "2024-04-25 12:00:00",
    P2: 3,
    P2_sumTime: "2024-04-25 08:00:00"
  }
]