How to add a number at the end of beginning of an array in JavaScript

I am trying to an update the “s” array with a function to be ordered from minor to major. But even though the if statement is true at the end of the loop ( 2 < 7 = true) it does not add the number at the beginning but at the end. Any advice?

const s = [5, 7, 2];

function editInPlace() {
  var newS = []
  for (let i = 0; i < s.length; i++) {
    if (console.log(s[i] < newS[i - 1])) {
      newsS.unshift(s[i])
      console.log("Evalute to true then add at the begining: " + newS.splice(s[i]));
    } else {
      newS.push(s[i]);
      console.log("newS es: " + newS)
    }
  }
}
editInPlace();

How can I add a YouTube embedded video to an image carousel? HTML / CSS

I have a carousel for a product and it has 1 image and 1 video. The image shows up alright but when I try to press on the video so it pops up into main carousel view, it doesn’t work. My index.html code (I omitted the actual video link from this source code) is:

<div id="content-wrapper">
    

    <div class="column">
        <img id=featured src="images/sample1.jpg">

        <div id="slide-wrapper" >
            

            <div id="slider">
                <img class="thumbnail active" src="images/sample1.jpg">
                <iframe class="thumbnail" width="560" height="315" src="videolink" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
            </div>

        </div>
    </div>

    <div class="col-2">
        <p>Home / Sample Item 1</p>
        <h1>Sample Item 1</h1>
        <h4>$00.00</h4>
        <h3>Product Details</h3><br>
        <p>Manufactured in CANADA</p>
    </div>

</div>

In the same source code I have a Javascript code:

<script type="text/javascript">
    let thumbnails = document.getElementsByClassName('thumbnail')

    let activeImages = document.getElementsByClassName('active')

    for (var i=0; i < thumbnails.length; i++){

        thumbnails[i].addEventListener('mouseover', function(){
            console.log(activeImages)
            
            if (activeImages.length > 0){
                activeImages[0].classList.remove('active')
            }
            

            this.classList.add('active')
            document.getElementById('featured').src = this.src
        })
    }


    let buttonRight = document.getElementById('slideRight');
    let buttonLeft = document.getElementById('slideLeft');

    buttonLeft.addEventListener('click', function(){
        document.getElementById('slider').scrollLeft -= 180
    })

    buttonRight.addEventListener('click', function(){
        document.getElementById('slider').scrollLeft += 180
    })


</script>

My CSS code:

body{
    padding-top: 100px;
}

#content-wrapper{
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
}

.column{
    width: 600px;
    padding: 10px;

}

#featured{
    max-width: 500px;
    max-height: 600px;
    object-fit: cover;
    cursor: pointer;
    border: 2px solid black;

}

.thumbnail{
    object-fit: cover;
    max-width: 180px;
    max-height: 100px;
    cursor: pointer;
    opacity: 0.5;
    margin: 5px;
    border: 2px solid black;

}

.thumbnail:hover{
    opacity:1;
}

.active{
    opacity: 1;
}

#slide-wrapper{
    max-width: 500px;
    display: flex;
    min-height: 100px;
    align-items: center;
}

#slider{
    width: 440px;
    display: flex;
    flex-wrap: nowrap;
    overflow-x: auto;

}

#slider::-webkit-scrollbar {
        width: 8px;

}

#slider::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);

}
 
#slider::-webkit-scrollbar-thumb {
  background-color: #dede2e;
  outline: 1px solid slategrey;
   border-radius: 100px;

}

#slider::-webkit-scrollbar-thumb:hover{
    background-color: #18b5ce;
}

.arrow{
    width: 30px;
    height: 30px;
    cursor: pointer;
    transition: .3s;
}

.arrow:hover{
    opacity: .5;
    width: 35px;
    height: 35px;
}

When I hover over the image – the image works and I can see it, but when I hover over the little embedded video, it gives a broken image sign in the main carousel view (above the thumbnail). What am I doing wrong? How can I make the video show up normally when I hover over it?

Nextjs Appdir export const revalidate = 0 gives 500 error when going directly to page

I have a checkout page in the appDir where I am fetching the paymentIntent from stripe. When I go by next navigation to the page it works correctly but if I go directly to example.com/checkout it gives me an internal server error 500 (A client-side exception has occurred). This issue only happens when deployed in my development environment I can go directly to localhost:3000/checkout without issue.

Code example:

import Stripe from 'stripe';
import Questionnaire from '../components/Questionnaire';

export const metadata = {
  title: 'Checkout',
  openGraph: {
    title: 'Checkout',
  },
  robots: {
    index: false,
    follow: false,
  },
};

export const revalidate = 0;

async function getStripeIntent() {
  const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

  return await stripe.paymentIntents.create({
    amount: 999,
    currency: 'usd',
  });
}

export default async function Page() {
  const { client_secret } = await getStripeIntent();

  return (
    <main className='container container--small'>
      <Questionnaire clientSecret={client_secret} />
    </main>
  );
}

I know what is causing the error is the line export const revalidate = 0 because when I remove it the page loads in production but then everyone would get the same stripe payment intent. As a workaround I have set the revalidate const to equal 0.01 but it would be much better if it was 0.

adding listeners to refs returned from custom hooks

I’ve set up a very basic custom hook in my React app intended to handle a given input element’s onChange events.

const useInput = () => {
    const ref = useRef(null);

    const handleChange = () => {
        console.log("Input updated");
    };

    useEffect(() => {
        const { current: input } = ref;
        // The script will never execute past this point.
        if(!input) return; 

        input.addEventListener("change", handleChange);
        return () => input.removeEventListener("change", handleChange);

    // Ref is stateless, so this won't trigger a re-run.
    }, [ref.current]);

    return { ref };
};

const Input = props => {
    const { ref: inputRef } = useInput();

    return (
        <input {...props} ref={inputRef} />
    );
};

The issue with my current implementation is that, by default, the ref will be null, and since refs are stateless, it will not re-execute that useEffect once the element does become available.

So, what is the best way to go about a case like this? Where I must return a ref to attach to the element.

Why is array undefined after I add an element to its index in an if-statement?

I have two if-statements and each add an element to the array at index 0 when you click on an element. The element in the array exists only within the if-statement that added it, I need it to exist in the whole scope.

if (compare == 'country' && typeof (array1[0]) == 'undefined') {
    console.log('you selected - ', array1[0], 
'and compare is ', compare, ' ', typeof(array1[0])) 
/* will say undefined which it is */

    array1[0] = compare

    console.log('you selected --- ', array1[0], 
'and compare is ', compare, ' ', typeof(array1[0])) 
/* now the array is defined */

}

if (compare == 'union' && typeof (array1[0]) == 'undefined') { 
/* here the array will count as undefined which I don't want. 
I want it to include the element from the previous if-statement */
    console.log('you selected ------ ', array1[0], 
'and compare is ', compare, ' ', typeof(array1[0]))
    array1[0] = compare
    console.log('you selected... ', array1[0], 'and compare is ', compare)

}

How do I make the array at index 0 retain the element that is set in any of these two if-statements? I want the scope to be global.

Higher order functions / closure in Javascript

In the example below, I was wondering what the difference would be between greet(‘Hello’) and greet(‘Hello’)(). I logged both to the console and greet(‘Hello’) showed Hello undefined but greet(‘Hello’)() showed undefined. I didn’t understand why that was happening. I’m confused on if the inner function is being invoked in greet(‘Hello’) situation although () is not explicitly written there, it seems that since greet(‘Hello’) is equal to function (name), this function is being invoked without (). With this reasoning, I’m not sure why greet(‘Hello’)() is showing undefined. Wouldn’t this just be passing in an undefined value and should therefore have the same result as greet(‘Hello’) which was Hello undefined, not undefined?

const greet = function (greeting) {
  return function (name) {
  console.log(`${greeting} ${name}`);
  }
}

greet('Hello')('Jonas');

greet('Hello')

greet('Hello')()

Hello Jonas

Hello undefined

undefined

What is the purpose of declaring all numbers your code is using in constants and then calling them everywhere in the code? This is in React JS

I work at a SaaS company where before I came on, 99% of the code was outsourced so I don’t have them to ask. The codebase I’m working on has a huge list of consts like this:

const NUMBER = {
  one: 1,
  two: 2,
  three: 3,
  .....
  forty: 40
}

This NUMBER const is used almost everywhere. For example, if there was a line of code accessing index 1 of an array, the code would be :

value = array[NUMBER.one];

These consts used to be everywhere, but I have been slowly phasing it out. These consts are used in HTML response status numbers like 200, 300, and even in default values for math calculations. I’m wondering if there is a good use for this coding practice that I’m just not seeing.

React native pdf – cannot view pdf in android

I am using react-native Expo, and using react-native-pdffor viewing the pdf.

However, in android device, users cannot view the pdf, but they can view the pdf in IOS device.

The url I am using:
http://content-dev.s3-website.ap-east-1.amazonaws.com/dev/CCCC.pdf

I am not sure if it’s because the url is not encrypted.

Does anyone know the reason?

  function showPdf() {
    const Pdf = require('react-native-pdf').default;
    return (
      <Pdf
        scale={1}
        trustAllCerts={false}
        cache={true}
        source={{
          uri: data.url,
        }}
      />
    );
  }

That’s what Android device shows
enter image description here

A The way to get the exact location for a device without a GPS unit (i.e. laptop) and based on the wifi connection

I am currently using:

navigator.geolocation.getCurrentPosition((position) => console.log({position});

this gives you a very wide guesstimate to your current location and cannot suffice for the application I’m builsing that would require a precise location of a max radius of 50 meters.
Navigator is half deprecated and just sits there with very basic usage, I tried passing certain variables I’ve found for more precision, yet either some were deprecated or weren’t producing any changes in precision of location.

We all know for a fact that (in most cases) your maps.google.com will have your pinpointed location on the map (blue dot) with ultra precision, and not only google applications, but other applications that have deep usage of your location (say uber for example) yet for some reason, I can’t get that through window.navigator.

It’s factual that some large tech companies like Google and Apple for instance have our exact location, on regular chrome websites (reminder; not on a device with a GPS), for instance – maps.google.com, you’ll have your location on the map with ultra precision (as a blue dot.

so this:

if ('connection' in navigator) {
  const networkInfo = navigator.connection;
  if (networkInfo.type === 'wifi') {
    const ssid = networkInfo.ssid;
    console.log('SSID:', ssid);
  }else{console.log('no');
}

will not work on any wifi I tried this on (approx 8)

So my question is: how do I get user BSSID connection like all large tech companies?

Call Lua function from an running script via an external program

Is there a way to call a lua function from an running script, with an input from another external non lua programm (js, python, c or c++ prefare)? The main problem is I can’t use any “middleman” like sockets or reading from an file. The one thing is both programms are running.
Is that possible?

I was thinking to trigger an event, but couldnt figuare it out how to make the input in runtime.

Faster way than map with includes?

I have the following example scenario:

var exampleArrayObjects = [{name: 'Example1'}, {name: 'Example2'}, {name: 'Example3'}];
var exampleArrayValues = ['Example1'];


var result = exampleArrayObjects.map((obj) => {
    if(exampleArrayValues.includes(obj.name)){
        return {
            ...obj,
            selected: true
        } 
    }else{
        return {
            ...obj,
            selected: false
        }
    }
})

console.log(result);

But in real life scenario, with large amount of data on “exampleArrayObjects” and “exampleArrayValues” it is taking a few minutes to get the result (a result object with additional attribute selected true/false according to the existance of the value).

Is there a faster way to get the same result?

UseFetch calling request immediately after changing parameters (Nuxt 3)

<template>
  <div>
    <div v-for="beer in beersResponse">{{ beer.name }}</div>
    <button @click="handleNextPage">Go to next page</button>
  </div>
</template>

<script lang="ts" setup>
const currentPage = ref(1);

const beerRequestParameters = computed(() => {
  return {
    per_page: 2,
    page: currentPage.value,
  };
});

const { data: beersResponse } = await useFetch(
  "https://api.punkapi.com/v2/beers",
  {
    params: beerRequestParameters,
  }
);

function handleNextPage() {
  currentPage.value += 1;
}
</script>

https://codesandbox.io/p/sandbox/usefetch-bug-forked-yyrjsy?file=%2Fapp.vue%3A13%2C17&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A3%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A3%7D%5D

UseFetch refreshing and calling request immediately after changing params.
What I want to do is to update params for that request and then call it later via refresh/execure function, but instead this request is called immediately after changing parameters.

It works as intended, page is changed after clicking the button, but i feel like it is not really readable, i would prefer to explicitly call function to fetch data with new parameters.

Is there any way to do it?

Why file uplaod does not work in solid.js?

I’m trying to make a simple multiple file upload usins solid.js like this:

import { createSignal } from 'solid-js';

function App() {

  const [files, setFiles] = createSignal([]);

  function handleFileChange(event) {
    const selectedFiles = Array.from(event.target.files);
    setFiles(() => selectedFiles);
    selectedFiles.forEach(file => {
      console.log('Selected file:', file.name);
      console.log('File size:', file.size);
    });
  }

  async function uploadFiles() {
    const formData = new FormData();
    for (const file of files()) {
      formData.append('file', file);
    } 

    // Send the file to the server using fetch or your preferred method
      try {
        const response = await fetch('http://127.0.0.1:8090/postme', {
          method: 'POST',
          body: formData,
        });
        console.log('File uploaded successfully');
      } catch (error) {
       console.error('Error uploading file:', error);
      }
  }

 
  return (
    <div class={styles.App}>
        <div class={styles.item}>
      
          <input type="file" multiple onChange={handleFileChange} />
          <button onclick={uploadFiles}>Upload</button>
         </div>
    </div>
  );
}

export default App;

In the console I see the file names and their sizes:

Selected file: Track01.mp3
App.jsx:16 File size: 1650939
App.jsx:15 Selected file: Track02.mp3
App.jsx:16 File size: 1919269
App.jsx:15 Selected file: Track03.mp3
App.jsx:16 File size: 1338305
App.jsx:37 File uploaded successfully

But in the backend empty files is received:

files: []

And no file is saved in the destination path.

I’ve also tried uploadFiles snycronously, but without luck.

I’m new to solid.js. Just wondering why this happens and how can I fix it?

lost with comparison expression in javaScript

I’m doing a challenge and I’ve been given this to resolve but I can’t find the error.

Declare a variable named speed and set it equal to 90.

Then declare a second variable named busExplodes and assign it the
result of a comparison expression that checks if speed is lesser than
80.

Print the result to the console.

var speed = 90;
var busExplodes = 80 < 90;
console.log (busExplodes);

I get this error: >>>>Code is incorrect Your condition should evaluate if speed is lesser than 80.

What am I doing wrong?