How to split an array to multiple arrays one by one JS

I need to split an Array into multiple arrays one by one, for example, if I have an array

const input = [1, 2, 3, 4, 5, 6, 7, 8, 9];

And the number of multiple arrays would be 3, the output should be

const arraysNumber = 3;
const result = [[1,4,7], [2,5,8], [3,6,9]];

if multiple arrays = 2,

const arraysNumber = 2;
result = [[1,3,5,7,9], [2,4,6,8]];

if multiple arrays = 4,

const arraysNumber = 4;
result = [[1,5,9], [2,6], [3,7], [4,8]];

I found only ways hot to split on chunks, like [[1,2,3], [4, 5, 6], [7, 8, 9]], but that’s not what I need

Would be grateful for any help!

GitHub API Pagination, possibly without relying on Link Header

I’m trying to paginate Issues’ Comments accordingly to their docs that relies on the Link Header.

I perform the Request using a (Babel) Class’ method, a wrapper routine for the Fetch API, like this:

class MyClass {

  async load( url, method = 'GET', args = {} ) {

    const options = {
      method: method.trim().toUpperCase(),
      redirect: 'follow'
    };

    try {

      const process = await fetch( url, Object.assign( options, args ) );

      if( ! process.ok ) {
        throw new Error( process.statusText );
      }
    
      return process.clone().json().catch( () => process.text() )

    } catch( error ) {
      return Promise.reject( error );
    }
  }

}

(new MyClass).load( 'https://api.github.com/repos/OWNER/REPOSITORY/issues/ISSUE/comments?page=1&per_page=15' );

I’ve suppressed a small bit of the code because, as you can see, I’m not returning the Fetch API Response Promise, only the resolved data, but I’ve tested it returning the thenable Promise itself and the results were the same.

For the sake of simplification, some simple debugging right after the process.ok yields me:

Response Object (console.log( process ))

{ type: "cors", url: "https://api.github.com/repos/OWNER/REPOSITORY/issues/ISSUE/comments?page=1&per_page=15", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false }

The Headers (iterating over process.headers.entries())

cache-control: private, max-age=60, s-maxage=60
content-type: application/json; charset=utf-8
etag: W/"5304658e191e2c59f9a26ca89366de5dcf3801d561b0307b0590282a672c4409"
x-accepted-oauth-scopes:
x-github-media-type: github.v3; param=html.squirrel-girl-preview; format=json
x-oauth-scopes: notifications, public_repo, user
x-ratelimit-limit: 5000
x-ratelimit-remaining: 4973
x-ratelimit-reset: 1638360867
x-ratelimit-resource: core
x-ratelimit-used: 27

x-ratelimit varies depending on the number of Requests performed within one hour

As you can see, no Link Header.

After some research, I’ve found this answer saying that over CORS only a few Headers are available and in its comments, I’ve learned that access-control-expose-headers when configured in the server can expand this list.

Well, this is a screenshot of the Response Data:

enter image description here

Once again, x-ratelimit varies

As you can see, Link is present among access-control-expose-headers, meaning that GitHub (apparently) did their part, and yet I can’t retrieve it.

With the case exposed so, how could I:

  • Get this Link Header using the Fetch API (preferably)
  • Or then build the pagination logic without it. Maybe using some math, perhaps?

What’s bugging me is that I’m 100% positive the very same code I have today was working ’til a few days ago when Firefox was updated. I’m sure of it because the whole implementation was working ’til 11/23, the date on which I’ve committed it to my repository.

In the meantime, Firefox was updated but I couldn’t find any information regarding a change in Fetch API, since I’ve read somewhere that using oldie XHtmlHttpRequest was still possible to get such headers.

‘Routes’ is not defined react/jsx-no-undef

So I was following the React Crash Course on YouTube for Beginners from Academind. I was following everything along and everything was good until I came to the Routing part.
I followed every step, everything just perfectly (for the routing part) but after refreshing the page the following error occurs:

A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.

Aaand I did it, I wrapped my Route in Routes :

    import { Route } from 'react-router-dom';


import AllMeetupsPage from './Pages/AllMeetups';
import NewMeetupsPage from './Pages/NewMeetups';
import FavoritesPage from './Pages/Favorites';

function App() {
  return (
    <div>
      <Routes>
        <Route path='/'>
          <AllMeetupsPage />
        </Route>

        <Route path='/new-meets'>
          <NewMeetupsPage />
        </Route>

        <Route path='/favs'>
          <FavoritesPage />
        </Route>
      </Routes>
    </div>
  );
}

export default App;

and then I get this:

‘Routes’ is not defined react/jsx-no-undef

then I :

Tried to import Routes from react-router-dom – No success;

Tried to import Routes from react-router – No success;

Tried to import Routes also in different components – No success;

Trust me I tried every different scenario for Routes but couldnt achieve anything different.
I

Googled, researched and couldnt find the solution for this problem.. Now Im desperate and
stuck here and I cant continue my React learning journey if I dont fix this…

Hovering tooltip position is not proper on ng2-charts (pie chart)

enter image description here

The hovering position is not proper on chart
When I am moving mouse from red color part to green color part, at the starting of green color it is still showing red color hovered and the green color will get hovered only when it reaches little right or center of the green color.
The position hovering is incorrect in this chart

”’

<canvas baseChart 
                    [data]="pieChartData" 
                    [labels]="pieChartLabels" 
                    [chartType]="pieChartType"
                    [options]="pieChartOptions"
                    [plugins]="pieChartPlugins"
                    [legend]="pieChartLegend"
                    [colors]="pieChartColors"
                    (chartClick)="statusClicked($event)">
                </canvas>

”’

Confused about this particular JavaScript way of expressing a function

I know there are different ways of declaring a function (or expressing it), however, I haven’t seen/used anything like this before (given, I am a “newbie” in the field). Can someone, please, explain how this particular function declaration works and when it is used? Can’t wrap my head around that “:” following function name!

const formSubmitHandler: SubmitHandler<IFormInputs> = () => {}

(Not sure if it has anything to do with typescript)

import './App.css';
import { useForm, SubmitHandler } from 'react-hook-form'

type IFormInputs = {
  email: string,
  password: string
}

const formSubmitHandler: SubmitHandler<IFormInputs> = (data: IFormInputs) => {
  console.log('the form data is', data);
}


const App = () => {
  const { register, handleSubmit, watch, formState: {errors}} = useForm<IFormInputs>()

  console.log(errors, 'this is an error explanation');
  console.log(watch('email'), 'watch the email variable');

  return (
    <div style={{padding: '2rem', border: '1px black solid'}}>
    <form onSubmit={handleSubmit(formSubmitHandler)}>
      <input defaultValue='[email protected]' {...register('email')}/>
      <br />
      {errors.password && <span>This field is required</span>}
      <br />
      <input {...register('password', { required: true })}/>
      <br />
      <br />
      <input type="submit" />
    </form>
    </div>
  )
}


export default App;  

Joi validation add rule only if property not undefined

I’m trying to implement the following validation rule using Joi.

Basically I have 2 properties a and b, I’d like to check that a is less than or equal to b only if b is not undefined.

Here is what I’ve tried so far:

const mySchema = Joi.object().keys({
    a: Joi.number().concat(Joi.number().when('b', { is: Joi.not(undefined), then: Joi.number().max(Joi.ref('b')).message('a should be less than or equal to b') })
    b: Joi.number() })

I get the following error message when testing the schema:

Cannot call allow/valid/invalid with undefined

Is it possible to terminate javascript code from runing from inside an async function

i want to terminate the javascript code from runing when a specific condition is satiesfied. But the problem is that the condition is inside an async function .

we can terminate the javascript from a normal function just by throwing an error but it does not work inside an async function.

if anyone can help me on this problem, it will be very helpful for me.
thanks in advanced.

Script must be prefetched but it doesn’t download

I want to prefetch one component for my application. And that’s how I’m trying to:

const Info = React.lazy(() => import(/* webpackPrefetch: true */ '@view/info/Info'));

Webpack use this magic comment to generate some links:

<link rel="prefetch" as="script" href="<href1>">
<link rel="prefetch" as="script" href="<href2>">
<link rel="prefetch" as="script" href="<href3>">

href1, href2 and href3 are working links and they lead to exsiting files.

But for some reason my chunk does not downloading until I try to use Info component.

What is the problem here?

i have a CSS button which i want to link to another html file without Javascript

i have a CSS button how to link to another html file without Javascript Note:
that i am not using html input or button html tags so i dont know how ,helpful if you would link a article or the solution code full
the html and css code below:

most of the code is just css animation from a site which is opensource and free

<!DOCTYPE html>
<html lang="en">
<body>

<h1 class="box-main"> Time :   9:30 AM </h1>
<h1 style="position:relative;  right:80px;  top:40px;" class="box-main">

</h1>

 <h1 class="box-main"> Date: 1 / 12 / 2021

 </h1>
 <h1 class="box-main"> Place: Random X and Z

 </h1>
</body>

    <meta charset="UTF-8">
    <title>Booking</title>
  <style>
    body {
    margin: 0;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: right;
    background-color: black;
    }

    nav ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
    }

    nav ul li {
        --c: white;
        color: var(--c);
        font-size: 16px;
        border: 0.3em solid var(--c);
        border-radius: 0.5em;
        width: 6em;
        height: 3em;
        text-transform: uppercase;
        font-weight: bold;
        font-family: sans-serif;
        letter-spacing: 0.1em;
        text-align: center;
        line-height: 3em;
        position: relative;
        overflow: hidden;
        z-index: 1;
        transition: 0.5s;
        margin: 1em;
    }

    nav ul li span {
        position: absolute;
        width: 20%;
        height: 100%;
        background-color: var(--c);
        transform: translateY(150%);
        border-radius: 50%;
        left: calc((var(--n) - 1) * 25%);
        transition: 0.5s;
        transition-delay: calc((var(--n) - 1) * 0.1s);
        z-index: -1;
    }

    nav ul li:hover {
        color: black;
    }

    nav ul li:hover span {
        transform: translateY(0) scale(2);
    }

    nav ul li span:nth-child(1) {
        --n: 1;
    }

    nav ul li span:nth-child(2) {
        --n: 2;
    }

    nav ul li span:nth-child(3) {
        --n: 3;
    }

    nav ul li span:nth-child(4) {
        --n: 4;
    }
    .box-main {
            display: flex;
            justify-content: center;
            align-items: center;
            text-align: center;
            color: White;
            max-width: 80%;
            margin: auto;
            height: 80%;
    }

    text-big {
        font-size: 10px;
    }



  </style>
</head>

<body>

<nav>
  <li>
    <ul>



<nav>
  <ul>
    <li>
     this is the button text

     book
      <span></span><span></span><span></span><span></span>


</body>
</html>

Thanks in advance please ask if you need any more information

Best way to catch an error in Models? (Node.js + Sequelize)

Is there a simple way to catch an error in an API (server) that’s using Node.js and Sequelize (Models)? Here is my code (it uses async + await):

const router = express.Router()
const { Operations } = require('../models')

router.post('/operations/add', async (req, res) => {
    const operations = req.body
    await operations.create(operations)
    res.json(operations)
    console.log('op added!')
})

router.put('/operations/update/:id', async (req, res) => {
    const operationId = req.params.id
    const operationUpdatedData = req.body
    const operationById = await Operation.findOne({ where: { id: operationId } })
    const operationUpdated = await operationById.update(operationUpdatedData)
    res.json(operationUpdated)
    console.log('op updated!')
})

router.delete('/operations/delete/:id', async (req, res) => {
    const operationId = req.params.id
    await Operations.destroy({ where: { id: operationId } })
    res.send('op deleted!')
    console.log('op deleted!')
})

module.exports = router

This is how I handle an error in the client:

axios.post(`http://localhost:9000/operations/add`, data)
            .then(res => console.log(`op added! (${res.status})`))
            .catch(err => console.log(`wrong! (${err.response.status} )`))

I don’t want anything fancy, but feel free to try whatever you want!

Remove missing Images from array React.js

I have array of images coming from external API, I want to filter images which are broken before showing them on carousel. as you can see now I map every image and showing MissingImage component as unloader if image is missing, but in my situation sometimes there are more than half images not available on API. how can I skip images if they aren’t available before passing them to Carousel component?

          {images.map((img, i) => (
        <Dot
          key={i}
          type="button"
          onClick={() => {
            setThumbsPosition(i);
            goToSlide(i);
            setActiveSlide(i);
          }}
          active={activeSlide === i}
          ref={i === 0 && slideRef}
        >
          <SliderDotImage>
            <Img
              loading="lazy"
              src={[img.url.bigger]}
              unloader={<MissingImage small />}
            />
          </SliderDotImage>
        </Dot>
      ))}

react variable not changing

in my react app i have got two files and, when value of (number) is changing in file App.js
in Form.js is still the same. What am i doing wrong?

App.js

import * as React from "react";
import { Form } from "./Components/Form";

function App() {
  
  let number = 0;
  const onInputChange = e => number = e.target.value;
    // number is changing every time i type something in
  return (
    <>
      <input onChange={onInputChange}></input>
      <Form number={number} />
    </>
  );
}

export default App;

Form.js

import React from "react";

export const Form =({number}) =>
{
    return(
        <h1>{number}</h1>
    )
}

onbeforeunload function fires on browser back button

We´re using following code to show a loading-modal if the loading of next page takes to long.

window.onbeforeunload = function () {
    window.setTimeout(showLoader, 2000);
}

function showLoader() {
    var loader = '<div id="layoutLoadingModal" class="modal fade" role="dialog">' +
        '<div class="modal-dialog">' +
            '<div class="modal-content">' +
                '<div class="modal-body">' +
                    '<h1>Loading!</h1>' +
                '</div>' +
            '</div>' +
        '</div>' +
    '</div>';
    $("body").append(loader);
    $('#layoutLoadingModal').modal('show');
}

Unfortunately it also shows the modal if the user uses the browser back button or a button with history.go(-1);
Is there any way to tweek the code to prevent this?