Clarifying “error-prone” nuance of spread syntax vs. assignment in Javascript

I know that the assignment of one variable to another is done by shared reference so that when you set var c = b; and then you do some change change to c such as c.cool = ‘new’; then b gets affected as well. console.log(b.cool); // new

However, coming to Javascript from different programming languages, I remember there is an error prone ‘gotcha’ when using the spread syntax var c = {…b}.

Can somebody clarify this ‘gotcha’?

Как сделать так чтоб когда я нажимал на div1 div2 исчезал – js [closed]

Я хочу, когда я кликаю на Div1, Div2 исчезал и наоборот

У меня есть 2 блока, нажимая на Div1 (style none) контента меняется на (style Block).И с Div2 также.
Я хочу что б нажимая на Div1 проверялся style Div2, и если style Div2 = Block менялся на none, и все наоборот. Система как в input radio

// FAQ1
function showDiv1(Div1) {
    var x = document.getElementById(Div1);
    if(x.style.display=="none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}


// FAQ2
function showDiv2(Div2) {
    var y = document.getElementById(Div2);
    if(y.style.display=="none") {
        y.style.display = "block";
    } else {
        y.style.display = "none";
    }
}

OpenLayers – “color-space/lchuv.js” not included in v8.2 download?

I’m just trying out some OpenLayers sample code (see below) with a download of version 8.2 but I get an error related to “color-space/lchuv.js” not found.

import Map from '/ol/Map.js';
import OSM from '/ol/source/OSM.js';
import TileLayer from '/ol/layer/Tile.js';
import View from '/ol/View.js';

const map = new Map({
   target: 'map',
   layers: [
     new TileLayer({
       source: new OSM(),
     }),
   ],
  view: new View({
    center: [0, 0],
    zoom: 2,
  }),
});

When I switched to a download of version 8.1 then the error disappears.

It seems to be a change to color.js. v8.2 references ‘color-space/lchuv.js’ which doesn’t seem to be included. v8.1 references math.js.

Am I doing something wrong or is there a directory missing from v8.2?

Xlsx downloaded file doesn’t open when download in the app, but does on the endpoint – Next/React, Spring Boot

In a Next/React front end app, with a Spring Boot API, I’m trying to export a list of users as a .xlsx file, generated in the API. When I download the file, I cannot open it, as I get the error “we found a problem with some content…” from Excel. However, using Insonmia, Postman or directly accessing the API endpoint on the browser, the file is downloaded and opens correctly.

It seems that the binary data is getting received as a string on the front end app, so the files gets corrupted when re-created. I’m using Axios.
Response data

What could be happening for it to work on Insonmia, Postman and the direct endpoint, but not on the front end app? In other projects, I handled the received file the same way and it always worked without much trouble, IIRC (but they used Node on the back end).

This is the Java Controller:
Export Controller

This is the front end request handler:
Axios request method

This is the download handler, on the React component:
Component Download Handler

I already tried changing the Controller to return a StreamingResponseBody converting the string to a Uint8Array, changing responseType to ‘arraybuffer’, creating the Blob with or without the type, but none worked.

Let me know if there is more information I could give to understand the context. Thanks.

want Bubble Confetti Effect for Button in ReactJS

Here I am creating a bubble confetti button effect using ReactJS. I want the effect of blowing up bubbles in all directions, so that when I click the button, bubbles will appear in the top, bottom, left, right, top-left, bottom-right corners, and size will vary and increase the number of bubbles. So how do you do that? Can you give me the solutions for that? Codes are given below.

import "./styles.css";
export default function App() {
  const animateButton = (e) => {
    e.preventDefault();
    e.target.classList.add("animate");
    setTimeout(function () {
      e.target.classList.remove("animate");
    }, 1000);
    let button = document.querySelector(".confetti-button");
    console.log(button);
  };

  return (
    <div className="App">
      <button onClick={animateButton} class="confetti-button">
        Click me!
      </button>
    </div>
  );
}

.confetti-button {
  width: 100px;
  border: none;
}
.confetti-button.animate {
  background-color: blue;
  color: white;
}
.confetti-button.animate:after,
.confetti-button.animate:before {
  content: "";
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  animation: animation ease-in-out 0.75s forwards;
}

@keyframes animation {
  0% {
    background-color: white;
    transform: translateY(0);
    opacity: 1;
  }
  100% {
    background-color: yellow;
    transform: translateY(-20px);
    opacity: 0;
  }
}

Javascript only doing one acton event

When the code is ran it only runs the first action and the second action doesnt run.

I have tried using code to make both run or the first then the second and the code isn’t running still. I am working with very little JavaScript knowledge because i haven’t learned it in school yet.

Player teleports when moving mouse upwards

Recently I have tried making a simple platformer game in kaboom js.
For some reason when I swiftly move the mouse upwards the player’s x position jumps from 400 to 2000 even though I don’t have anything that detects mouse movement.

kaboom({
 background: [134, 135, 247],
 width: 800,
 height: 800,
 
 
});
var preference = localStorage.getItem('outfit');
if(null === preference)
{
    localStorage.setItem("outfit",0)
}
loadSound( "background", "bg.wav" );
const music = play("background", {
    volume: 0.8,
    loop: true
})

onLoading((progress) => {

    // Black background
    drawRect({
        width: width(),
        height: height(),
        color: rgb(0, 0, 0),
    })

    // A pie representing current load progress
    drawCircle({
        pos: center(),
        radius: 32,
        end: map(progress, 0, 1, 0, 360),
    })

    drawText({
        text: "loading" + ".".repeat(wave(1, 4, time() * 12)),
        font: "monospace",
        size: 24,
        anchor: "center",
        pos: center().add(0, 70),
    })

})
setGravity(1600)
let outfits=["tommy/normal.png","tommy/drip.png"]
loadSpriteAtlas(outfits[parseInt(localStorage.getItem("outfit"))], {
  "left": {
    "x":0,
    "y":0,
    "width": 96,
    "height": 80,
    "sliceX": 3,
    "anims": {
      "run": {
        "from": 0,
        "to": 2,
        "speed": 15,
        "loop":true
      },
      "idle": {
        "from": 1,
        "to": 1,
        "speed": 15,
        "loop":true
      },
      "jump": 1
    }
  },

})
loadSprite("grass","grass.png")


const level = addLevel([
  "                  ",
  "                  ",
  "                  ",
  "                  ",
  "                  ",
  "                  ",
  "                  ",
  "                  ",
  "                  ",
  "                  ",
  "                  ",
  "                  ",
  "                  ",
  "                  ",
  "==================",
  "==================",
  "==================",
  "==================",
  "==================",
], {
  // The size of each grid
  tileWidth: 48,
  tileHeight: 48,
  // The position of the top left block
  pos: vec2(0,0),
  // Define what each symbol means (in components)
  tiles: {

    "=": () => [
      sprite("grass"),
      area(),
      scale(3),
      body({ isStatic: true }),
      anchor("bot"),
    ],

  },
})
const player = add([
  sprite("left", { anim: "idle" }),
  pos(center()),
  area(),
  scale(2),
  body(),
]) 
onKeyRelease("right", () => {player.play("idle")})
onKeyRelease("left", () => {player.play("idle")})
onKeyDown("right", () => {
  player.flipX=false;
  player.move(500*dt()*30,0)
  if(player.curAnim() !== "run"){
    player.play("run")
  }

})
onUpdate(() => {
  debug.log(player.pos)
})
let timee=0;

onKeyPress("space", () => {
  if(player.isGrounded()){
    player.jump()
  }


})

onKeyDown("left", () => {
  player.flipX=true;
  player.move(-500*dt()*30,0)
  if(player.curAnim() !== "run"){
    player.play("run")
  }

})

I tried limiting the player’s x so the player cannot go off screen but the code was messy and it did not really work.

How to Shuffle div on each new page visit

I have code to shuffle my div on reload, but I want to instead have it shuffle on each new page visit. I am no pro in jquery/javascript so came here to ask for some advice.

Here’s my jsfiddle code

jsfiddle

I tried adding this but it just keeps reloading my page in kartra.

<script>
      $(document).ready(function() {
          window.location.href = window.location.href;
      });
</script>

Ackermann with for loops only?

I thought Ackermann’s function couldn’t be implemented using only for loops, but I came up with an implementation that uses only higher-order functions and two nested for loops (no recursion, no while loop, no explicit stack).
I guess there’s an implicit stack when the program creates a new function on each iteration of one of the loops, but I think it’s still interesting.
Code below:

// helper function: applies a function n times using a for loop
const repeatFunc = (n, val, fun) => {
    for (let i = n; i > 0; i--) {val = fun(val)}
    return val
}

const ackermann = (m, n) =>
    (repeatFunc(m, (n) => n+1, (prevAck) =>
        (n) =>
            repeatFunc(n, prevAck(1), (n) =>
                prevAck(n)))
    )(n);

Vite and React Issue: ‘text/jsx’ MIME Type Error with ReactDOM.createRoot

I’m encountering an issue while using Vite and React in my project. Specifically, I’m getting a MIME type error (‘text/jsx’) when trying to render my application using ReactDOM.createRoot. This issue is impacting the proper execution of my React application.

I’ve followed all the procedures, but my page isn’t displaying. Even tutorials are not working. I need help with this.

Conditional image with routing

I have a home route and a chat route. I want to see a different image in my navbar when I go to the chat route

Here’s the code:

import { Container, Nav, Navbar } from "react-bootstrap";
import logo from "../assets/Logo.png";
    
const Header = () =>{
  return(
    <Navbar bg="dark" variant="dark" expand="lg" className="mx-auto">
      <Container>
        <Navbar.Brand href="/">
          <img src={logo} alt="Home" width={270}/> // This is the image
        </Navbar.Brand>

        <Navbar.Collapse>
          <Nav className="ms-auto">
            <Nav.Link href="/">Home</Nav.Link>
            <Nav.Link href="/chat">Chat</Nav.Link>
          </Nav>
        </Navbar.Collapse>
      </Container>
    </Navbar>
  )
}
export default Header;

Why is TypeScript not detecting implicit use of any in nested object/array properties?

Why is Typescript not detecting that I’ve checked only part of unknown type, and not it’s nested properties thus resulting in runtime error?

interface User {
    name: string,
    age: number
}

const externalData: unknown = [1, 2, 3];

(Array.isArray(externalData) ? externalData : [])
    .reduce<User[]>((acc, curr) => {
        return [
            ...acc,
            {
                name: curr.some.nested.property, // not detecting that these properties may not exist on type 'any'
                age: curr.some.nested.another.propety // not detecting that these properties may not exist on type 'any'
            }
        ]
    }, []);

Detect favicon change in userscript

I am writing a Tampermonkey userscript, and I need to fire a function on each time the pages favicon changes.

For example:

  1. Script on the page changes the pages favicon to another one
  2. The userscript detects that, or gets an event of it happening
  3. The userscript triggers myFunction()

The favicon on the page is set like this:
<link rel="shortcut icon" href="/dstatic/favicon.ico" type="image/x-icon" crossorigin="anonymous">

I tried to use Proxy objects:
var targetObj = document.querySelectorAll('[rel="shortcut icon"]')[0]; var targetProxy = new Proxy(targetObj, { set: function (target, key, value) { console.log("Favicon changed"); target[key] = value; return true; } });

I expected:
console.log("Favicon changed"); fires on favicon change from the pages script.
Result:
This only happens when you call targetProxy.href. If you call it with anything other than targetProxy, which is what the page itself does, it does not work.