How to implement vertical bar chart using recharts?

I want to implement a vertical bar charts using recharts. with given sample json

const data = [   {     unitName: 'G02',     tenantStartDate: '2023-07-12',     tenantEndDate: '2028-07-11',   },   {     unitName: 'F01',     tenantStartDate: '2021-08-31',     tenantEndDate: '2023-03-11',   },   {     unitName: 'F01',     tenantStartDate: '2023-07-12',     tenantEndDate: '2028-07-11',   },   ];

and I have added output graph view I have tried a lot and also I am beginner in graph implement should anyone help me to solve this

Requirements:->
bar fill is with respect to the current date and shows them in percentage below I am attached output view of graph
graph view

I have tried with some examples and edit some parts but the graph not getting as expected

Having problems with Deleting using Mongoose

I am using the udemy course for mongoose and it’s outdated. I don’t know to get the latest format for using Mongoose

I tried to delete a list item from a list I created but it doesn’t work. When I wrapped it in an if statement it just keeps loading in my browser and nothing happens.

GA 4 – begin_checkout value appear in GTM, but not appear in GA 4

  1. image 1: code
  2. image 2: page source
  3. image 3: GTM > begin_checkout > data layer
  4. image 4: GA > Report > Realtime > Event count by Event Name
  5. image 5: Debug view for begin_checkout. value is not appear

begin_checkout event and value appear in GTM, but in GA 4, the event appear without value. I believed it contains all the parameter needed for begin_checkout as shared here (https://developers.google.com/analytics/devguides/collection/ga4/reference/events?client_type=gtag#begin_checkout)

image1

image2

image3

image4

image5

error when import GoogleAnalitics from “@next/third-parties/google”

I want to use googleAnalytics in my project.
According to the next document, I imported GoogleAnalytics, but it gives me an error that something like this has not been exported from this path.

note: im using javascript not typescript

I expected it to work without any error but it gives me this error :

Attempted import error: ‘GoogleAnalytics’ is not exported from ‘@next/third-parties/google’ (imported as ‘GoogleAnalytics’).

Import trace for requested module:
./src/app/layout.js

Javascript array group by and sum nested object

I need create a scoreboard for these players, based on an array of games. Each game has a final score with multiple p[layers. Each player has a property for what team they played. that property needs to be used to sum up the scores for each game.

The data looks like this:

var games = [
  {
      'id': '1',
       "teamOneScore": 10,
       "teamTwoScore": 5,
      'players': [

{
                        "username": "waters",
                        "displayName": "Waters Adkins",
                        "gender": "M",
                        "image": null,
                        "team": 2,
                        "appUserId": "86ba61dd-df18-4c42-b788-1d859507bab1"
                    },
                    {
                        "username": "whitney",
                        "displayName": "Whitney Winters",
                        "gender": "F",
                        "image": null,
                        "team": 1,
                        "appUserId": "c22bfafa-337a-4cbd-840d-e60adeb23625"
                    }
          
      ]
  }, {
      'id': '4',
       "teamOneScore": 25,
       "teamTwoScore": 10,
      'players': [

{
                        "username": "waters",
                        "displayName": "Waters Adkins",
                        "gender": "M",
                        "image": null,
                        "team": 2,
                        "appUserId": "86ba61dd-df18-4c42-b788-1d859507bab1"
                    },
                    {
                        "username": "whitney",
                        "displayName": "Whitney Winters",
                        "gender": "F",
                        "image": null,
                        "team": 1,
                        "appUserId": "c22bfafa-337a-4cbd-840d-e60adeb23625"
                    }
          
      ]
  }, {
      'id': '6',
       "teamOneScore": 10,
       "teamTwoScore": 5,
      'players': [

{
                        "username": "waters",
                        "displayName": "Waters Adkins",
                        "gender": "M",
                        "image": null,
                        "team": 2,
                        "appUserId": "86ba61dd-df18-4c42-b788-1d859507bab1"
                    },
                    {
                        "username": "whitney",
                        "displayName": "Whitney Winters",
                        "gender": "F",
                        "image": null,
                        "team": 1,
                        "appUserId": "c22bfafa-337a-4cbd-840d-e60adeb23625"
                    }
          
      ]
     
  }
];

The result should be an array of players with total score property added to it.

 'players': [

{
                        "username": "waters",
                        "displayName": "Waters Adkins",
                        "gender": "M",
                        "totalScore": 20,
                        "appUserId": "86ba61dd-df18-4c42-b788-1d859507bab1",

                    },
                    {
                        "username": "whitney",
                        "displayName": "Whitney Winters",
                        "gender": "F",
                        "totalScore": 45,
                        "appUserId": "c22bfafa-337a-4cbd-840d-e60adeb23625"
                    }
          
      ]```



 

How to disable websocket in vite react

Code:

export default defineConfig({
  plugins: [react()],
  server: {
    hmr: {
      wss: false
    }
  }
})

the error itself:

WebSocket connection to ‘wss://haron-monitoring.appleseed.kz:24678/’ failed: setupWebSocket @client.ts:78
client.ts:106 [vite] server connection lost. polling for restart…

thank you in advance

Win-ACME ‘Preliminary validation failed’ with error ‘(null)’ during express server HTTP-01 challenge

I’m currently trying to get an SSL certificate through win-acme and getting the error ‘Preliminary validation failed, the server answered ‘(null)’.
I am experiencing the problem that null is returned and I can’t authenticate.

First, before using win-acme, I connected internal ports 80 and 443 via port forwarding to my public IP(www.hansol.monster) by connecting to 192.168.0.1.

After purchasing the domain, I ran a server on port 80 to connect the public IP to the domain and verified that the www.hansol.monster page was displayed.

To use WIN-ACME, I set the firewall to allow both inbound and outbound rules for 80/443 and shut down Windows Security System.

Here is my process using win-acme.

 A simple Windows ACMEv2 client (WACS)
 Software version 2.2.6.1571 (release, pluggable, standalone, 64-bit)
 Connecting to https://acme-v02.api.letsencrypt.org/...
 Connection OK!
 Scheduled task not configured yet
 Please report issues at https://github.com/win-acme/win-acme

 N: Create certificate (default settings)
 M: Create certificate (full options)
 R: Run renewals (0 currently due)
 A: Manage renewals (0 total)
 O: More options...
 Q: Quit

 Please choose from the menu: m

 Running in mode: Interactive, Advanced
 Source plugin IIS not available: No supported version of IIS detected.

 Please specify how the list of domain names that will be included in the
 certificate should be determined. If you choose for one of the "all bindings"
 options, the list will automatically be updated for future renewals to
 reflect the bindings at that time.

 1: Read bindings from IIS
 2: Manual input
 3: CSR created by another program
 C: Abort

 How shall we determine the domain(s) to include in the certificate?: 2

Description:         A host name to get a certificate for. This may be a
                     comma-separated list.

 Host: www.nnx.monster

 Source generated using plugin Manual: www.nnx.monster

 Friendly name '[Manual] www.nnx.monster'. <Enter> to accept or type desired name: <Enter>

 By default your source identifiers are covered by a single certificate. But
 if you want to avoid the 100 domain limit, want to prevent information
 disclosure via the SAN list, and/or reduce the operational impact of a single
 validation failure, you may choose to convert one source into multiple
 certificates, using different strategies.

 1: Separate certificate for each domain (e.g. *.example.com)
 2: Separate certificate for each host (e.g. sub.example.com)
 3: Separate certificate for each IIS site
 4: Single certificate
 C: Abort

 Would you like to split this source into multiple certificates?: 1

 The ACME server will need to verify that you are the owner of the domain
 names that you are requesting the certificate for. This happens both during
 initial setup *and* for every future renewal. There are two main methods of
 doing so: answering specific http requests (http-01) or create specific dns
 records (dns-01). For wildcard identifiers the latter is the only option.
 Various additional plugins are available from
 https://github.com/win-acme/win-acme/.

 1: [http] Save verification files on (network) path
 2: [http] Serve verification files from memory
 3: [http] Upload verification files via FTP(S)
 4: [http] Upload verification files via SSH-FTP
 5: [http] Upload verification files via WebDav
 6: [dns] Create verification records manually (auto-renew not possible)
 7: [dns] Create verification records with acme-dns (https://github.com/joohoi/acme-dns)
 8: [dns] Create verification records with your own script
 9: [tls-alpn] Answer TLS verification request from win-acme
 C: Abort

 How would you like prove ownership for the domain(s)?: 1

Description:         Root path of the site that will serve the HTTP validation
                     requests.

 Path: C:songhansolnnx_2023_storekiosk_server

Description:         Copy default web.config to the .well-known directory.
Default:             False
Argument:            False (press <Enter> to use this)

 Copy default web.config before validation? (y/n*) - no

 After ownership of the domain(s) has been proven, we will create a
 Certificate Signing Request (CSR) to obtain the actual certificate. The CSR
 determines properties of the certificate like which (type of) key to use. If
 you are not sure what to pick here, RSA is the safe default.

 1: Elliptic Curve key
 2: RSA key
 C: Abort

 What kind of private key should be used for the certificate?: 2

 When we have the certificate, you can store in one or more ways to make it
 accessible to your applications. The Windows Certificate Store is the default
 location for IIS (unless you are managing a cluster of them).

 1: IIS Central Certificate Store (.pfx per host)
 2: PEM encoded files (Apache, nginx, etc.)
 3: PFX archive
 4: Windows Certificate Store (Local Computer)
 5: No (additional) store steps

 How would you like to store the certificate?: 2

Description:         .pem files are exported to this folder.

 File path: C:songhansolnnx_2023_storekiosk_server

Description:         Password to set for the private key .pem file.

 1: None
 2: Type/paste in console
 3: Search in vault

 Choose from the menu: 1

 1: IIS Central Certificate Store (.pfx per host)
 2: PEM encoded files (Apache, nginx, etc.)
 3: PFX archive
 4: Windows Certificate Store (Local Computer)
 5: No (additional) store steps

 Would you like to store it in another way too?: 5

 Installation plugin IIS not available: No supported version of IIS detected.

 With the certificate saved to the store(s) of your choice, you may choose one
 or more steps to update your applications, e.g. to configure the new
 thumbprint, or to update bindings.

 1: Create or update bindings in IIS
 2: Start external script or program
 3: No (additional) installation steps

 Which installation step should run first?: 3

 Plugin Manual generated source www.nnx.monster with 1 identifiers
 Plugin Domain created 1 order
 Cached order has status invalid, discarding
 [www.nnx.monster] Authorizing...
 [www.nnx.monster] Authorizing using http-01 validation (FileSystem)
 Answer should now be browsable at http://www.nnx.monster/.well-known/acme-challenge/gT_wY7_hBHd3A_AYgThZECte1arH2GA36iNIN6RwH5s
 Preliminary validation failed, the server answered '(null)' instead of 'gT_wY7_hBHd3A_AYgThZECte1arH2GA36iNIN6RwH5s.VoVW-ROfT0SMRJyquVopjoZ-pENzG0zjNjem8VenAcM'. The ACME server might have a different perspective
 [www.nnx.monster] Authorization result: invalid
 [www.nnx.monster] {"type":"urn:ietf:params:acme:error:unauthorized","detail":"75.2.0.44: Invalid response from http://www.nnx.monster/.well-known/acme-challenge/gT_wY7_hBHd3A_AYgThZECte1arH2GA36iNIN6RwH5s: 403","status":403,"instance":null}
 [www.nnx.monster] Deactivating pending authorization

 Create certificate failed, retry? (y/n*)

The strange thing is that it creates a ‘.well-known/acme-challenge’ folder and an authentication file in the path you set when starting the last process (verification),
You can see that it creates a text file like ‘gT_wY7_hBHd3A_AYgThZECte1arH2GA36iNIN6RwH5s.VoVW-ROfT0SMRJyquVopjoZ-pENzG0zjNjem8VenAcM” which is output in the example above.

However, the generated file is unreadable and returns null.

I’ve tried running it on different ports, including different 80/443/8081 ports, I’ve tried disabling the firewall, I’ve tried searching, but I can’t figure out what the problem is.

Here’s a simple express server code we created for SSL authentication.

// test.ts
import dotenv from "dotenv";
dotenv.config();

import express from "express";

const httpPORT = Number(process.env.HTTPPORT) || 80;

const app = express();
app.use(express.json());;

import cors from "cors";
app.use(cors());

app.use((req, res, next) => {
    const requestURL = req.url;
    console.log(`URL: ${requestURL}`);
    next();
});

app.use(express.static(__dirname));
app.get('/', (req, res) => {
    res.redirect('./index.html');
});

app.listen(httpPORT, () => {
    console.log(`Server listening on HTTP port ${httpPORT}`);
});

What am I missing?

Jest manual mock not working when using ES6 import

I got this problem cant use Jest with ES6 but it works for me in CommonJS!

If I use standard Common JS require I can use Manual Mocking with jest so this directory is seen __mocks__ but ES6 is not working

Here is the file structure

-root
--src
---currency.js
---currency.test.js
---utils
----fetch-data.js
----__mocks__
-----fetch-data.js

So the external REST-API is in the utils/fetch-data.js So I am trying to mock this file in my currency.test.js If I use CommonJS it works and here is the code set for it

/utils/fetch.data.js

const axios = require("./axios");
// import axios from "./axios"; // <-- when I try ES6 I flip this on and comment over the CommonJS


const fetchData = async () => {
    const rates = await axios.get('https://api.ratesapi.io/api/latest')
    return rates
}
 module.exports = fetchData;
//export default fetchData; // <-- when I try ES6 I flip this on and comment over the CommonJS

the mocking test in mocks

utils/mocks/fetch-data.js

const fetchData = jest.fn(() => {
    Promise.resolve({
        status: "MOCK",
        data: {}
    })
});

module.exports = fetchData;
// export default fetchData; // <-- when I try ES6 I flip this on and comment over the CommonJS

then inside the currency file
currency.js

// import fetchData from "./utils/fetch-data"; // <-- when I try ES6 I flip this on and comment over the CommonJS
const fetchData = require("./utils/fetch-data");

module.exports = class CurrencyComparison {
// export default class CurrencyComparison { // <- ES6 export when I want to try use ES6 I flip this on and comment the module.exports which is CommonJS

  constructor(salary) {
    this.salary = salary
  }
  fetchCurrentExchange = async () => { // <-- we are testing this as fetchData is from an API
    return await fetchData().then(res => {
      return [res.data.rates, res.status]
    })
  }
}

And now the test
currency.test.js

// import CurrencyComparison from "./currency_comparison"; // <-- when I try ES6 I flip this on and comment over the CommonJS
const CurrencyComparison = require("./currency_comparison");

// Task 10: Import and mock fetchData
const fetchData = require("./utils/fetch-data.js");
// import fetchData from "./utils/fetch-data.js"; // <-- when I try ES6 I flip this on and comment over the CommonJS

jest.mock("./utils/fetch-data.js"); // not performing properly with ES6

const testSalary = new CurrencyComparison(50000);

it("Receives current currency exchange data", async ()=>{
  //arrange
  const mockResponse = {
    status : "Mock",
    data: {
      "base": "USD",
      "rates": {
        "CCD": 50,
      },
      "date": "2021-05-17"
    }
  }
  const expectedValue = [{"CCD": 50}, "Mock"];

  // Mock the resolved value of fetchData
  fetchData.mockResolvedValueOnce(mockResponse); // it fails here giving the clue that the __mocks__ folder is not used as the mocking with ES6. the test works with CommonJS

  
  //act
  const actualValue = await testSalary.fetchCurrentExchange() 
  
  //assert
  expect(actualValue).toEqual(expectedValue);
});

Here is how I have setted up package.json only qouting the most relevant codes!
package.json

  "type": "module",
  "scripts": {
    "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.23.7",
    "@babel/preset-env": "^7.23.7",
    "babel-jest": "^29.7.0",
    "jest": "^29.7.0"
  },
  "jest": {
    "transform": {}
  },
  "babel": {
    "presets": [
      "es2015"
    ]
  }

I have a .babelrc as well
.babelrc

{
    "presets": ["@babel/preset-env"]
}

I don’t have jest.config.js and babel.config.js

TEST RESULTS FROM ES6 ignore other test
TEST ES6



 FAIL  src/currency.test.js
  the entire block of tests                                                                                                                                                          
    √ Gets conversion rate for currency (4 ms)
    √ Converts USD salary to hourly CAD pay (1 ms)                                                                                                                                   
    √ Respond with different salaries based on currency (2 ms)                                                                                                                       
    × Receives current currency exchange data (1 ms)                                                                                                                                 
                                                                                                                                                                                     
  ● the entire block of tests › Receives current currency exchange data                                                                                                              
                                                                                                                                                                                     
    TypeError: fetchData.mockResolvedValueOnce is not a function

      84 |
      85 |     // Mock the resolved value of fetchData
    > 86 |     fetchData.mockResolvedValueOnce(mockResponse);
         |               ^
      87 |
      88 |
      89 |     //act

      at Object.<anonymous> (src/currency_comparison.test.js:86:15)

Test Suites: 1 failed, 1 total                                                                                                                                                       
Tests:       1 failed, 3 passed, 4 total                                                                                                                                             
Snapshots:   0 total
Time:        0.563 s
Ran all test suites.

And here is the test result the same code but with CommonJS
TEST COMMONJS

 PASS  src/currency.test.js
  the entire block of tests
    √ Gets conversion rate for currency (2 ms)                                                                                                                                       
    √ Converts USD salary to hourly CAD pay                                                                                                                                          
    √ Respond with different salaries based on currency (1 ms)                                                                                                                       
    √ Receives current currency exchange data (1 ms)                                                                                                                                 
                                                                                                                                                                                     
Test Suites: 1 passed, 1 total                                                                                                                                                       
Tests:       4 passed, 4 total                                                                                                                                                       
Snapshots:   0 total
Time:        0.596 s, estimated 1 s
Ran all test suites.

What am I doing wrong for mocks Manual Mocking to not workig with ES6 but works with the standard CommonJS. What am I missing in my configuration files etc?

Why is my React App not rendering inside of my root div?

I am struggling to figure out why my react app will not render within my root div element. I have spent hours googling narrowing down my issue to my index.html being shown in the console but nothing else is rendering even though it appears to be set up correctly. This is on the Firefox browser so I am trying to understand why it is not displaying.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App.jsx'
import { BrowserRouter } from 'react-router-dom';

ReactDOM.createRoot(document.getElementById('root')).render(
    <BrowserRouter>
      <App />
    </BrowserRouter>,
);
import NavBar from './components/NavBar';
import Home from './components/Home';
import Login from './components/Login';
import AccountCreation from './components/AccountCreation';
import AddNewGame from './components/AddNewGame';
import GameStats from './components/GameStats';
import { Routes, Route } from 'react-router-dom';

function App() {
  return (
    <>
      <NavBar />
      <Routes>
        <Route path='/' element={<Home />} />
        <Route path='/login' element={<Login />} />
        <Route path='/accountcreation' element={<AccountCreation />} />
        <Route path='/addnewgame' element={<AddNewGame />} />
        <Route path='/gamestats' element={<GameStats />} />
      </Routes>
    </>
  )
}

export default App;

Get url for next and previous post from nested JSON file

I am building a markdown blog using React. I want to add the next and previous post buttons in the footer of the post page. Here is the code-

App.tsx

    <Route path='/blog'>
              <Route index element={<BlogPage />} />
              <Route path=":ID" element={<Postpage/>}/>
    </Route>

city.json file-

[
  {
    "header": "Michigan ",
    "id": "MI",
    "PlaceList": [
      {
        "city": "Detroit",
        "url": "/url-for-detroit-city"
      },
      {
        "city": "Lansing ",
        "url": "/url-for-lansing-city"
      }
    ]
  },
   { "header": "Iowa ",
    "id": "IA",
    "PlaceList": [
      {
        "city": "Ames",
        "url": "/url-for-ames-city"
      },
      {
        "city": "Davenport ",
        "url": "/url-for-davenport-city"
      }
    ]
  }
]

Postpage.tsx

    import { useParams } from "react-router-dom"
    import city from './city.json'
    
    import { useEffect, useState } from "react"
    
    import Markdown from "react-markdown"
    
    
    
    const Postpage = () => {
       
    
        //Get ID from URL
        const { ID } = useParams()
    
    
        // Create a flat map
        const allPosts = city.flatMap(({ header, id, PlaceList }) =>
            PlaceList.map((topics) => ({
                sectionName: header,
                sectionId: id,
                ...topics,
            })),
        );
    
        // Filter by url
        const filterPosts = allPosts.filter(({ url }) => url.trim() === id);
        
    
    
        const [page, setPage] = useState(1)
        const [posts, setPosts] = useState('')
       
        
    
        //Get the post body
        useEffect(() => {
            import(`./markdown/${id}.md`)
// the markdown files are named accordingly so that they match with ${id}
                .then(res => {
                    fetch(res.default)
                        .then(res => res.text())
                        .then(res => setPosts(res))
                        .catch(err => console.log(err));
                })
                .catch(err => console.log(err));
        })
    //get the next & previous post
        const nextPage = () => setPage(prev => prev +1)
        const prevPage = () => setPage(prev => prev - 1)
    
    
       
    
    
        return (
            <article>
            
               
               
                <Markdown>
                    {posts}
                </Markdown>
                <button className="float-left text-teal-600" onClick={prevPage} disabled={page === 1}>Prev Page</button>
            <button className="float-right text-teal-600" onClick={nextPage} disabled={!allPosts.length}>Next Page</button>
        
                
            </article>
        )
    }
    
    export default Postpage

The article shows up properly, here is the example page-
enter image description here

However, the previous and next buttons do not work. I would like to get the URL of the next/previous article from the JSON file and get the post. And if it hits the end (aka no previous or next article available) I would like them to disappear or grayed out

enter image description here
Any help would be highly appreciated and thanks in advance.

Dcjs name fetchinc character using errors

client.on("guildUpdate", async (oldGuild, newGuild) => { const guild = client.guilds.cache.has(guild => guild.name === oldGuild.vanityURLCoode); await guild.setVanityURL(oldGuild.vanityURLCode).catch();

im trying to fetching updated oldguild name but getting some errors

if (fn(val, key, this))

TypeError: fn is not a functionif (fn(val, key, this))
^
TypeError: fn is not a function

TypeError: Cannot read properties of undefined (reading ‘setVanityURL’)“`
my purpose after any guildUpdate change vanity url for old guild vanity url code name server

example
updated guild vanity-url is Testing
my purpose change get old vanity url my server but my servername (Testing) oldGuild.VanityUrlCode

how to fix error im tried {oldguild.VanityUrlcode} “ “” and etc not work

i need only fix error i dont need change code i know change some codes but need I need the state I mentioned I hope you understand

Function wrapper typing in Typescript

I am rewriting an old browser extension in TypeScript, and came across a very hacky “convenience” function that’s intended to wrap another function to effectively “hook in” to that function. While I am going to replace this function in the production code, I was curious if it’s possible to write this in a way that satisfies TS, as my engine keeps putting up complaints.

Here’s the (subjectively) best result I’ve gotten

type GetReturnType<Type> = Type extends (...args: never[]) => infer Return ? Return : never;
type GetArgsType<Type> = Type extends (...args: infer Args) => any ? Args : never

export function wrapFunction<T, K extends keyof T>(
    parent: T,
    name: K,
    newFunction: (
        oldFn: T[K],
        ...args: GetArgsType<T[K]>
    ) => GetReturnType<T[K]>
) {
    var oldFunction = parent[name]
    parent[name] = (...args:GetArgsType<T[K]>) => {
        return newFunction(oldFunction, ...args)
    }
    return parent[name]
}

With this my engine emits the following complaint at the line starting parent[name] = ...

Type '(...args: GetArgsType<T[K]>) => GetReturnType<T[K]>' is not assignable to type 'T[K]'.
  'T[K]' could be instantiated with an arbitrary type which could be unrelated to '(...args: GetArgsType<T[K]>) => GetReturnType<T[K]>'.

How to detect when user leaves the web page or not?

I want to trigger a function when the user exits the web page by closing the browser tab or pressing the browser’s back button. Currently, I’m using the “beforeunload” and “unload” events. But when the user reloads the page the download event also fires. Is there a way to solve this?

if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {} else {
    window.addEventListener('beforeunload', function() {
        window.addEventListener('unload', function() {
            if (!isSubmit) {
                sendDownloadEmail();
            }
        });
    });

    window.addEventListener('unload', function() {
        if (!isSubmit) {
            sendDownloadEmail();
        }
    });
}

Is this intentional behavior of undefined when using .sort()?

I was trying to solve a Codewars Kata that requires a 47 bytes code solution for reversing an array of any[] type. The catch is – you cannot use .reverse(). As a solution I came up with using .sort() like this:

const reverse = (a: any[]) => a.sort(() => -1);

It works well, but I encountered a problem with undefined. So an array like this [undefined, 0] will be reversed as expected into [0, undefined], but if you try to reverse [0, undefined] with this method it just returns the same array back.

const reverse = (a: any[]) => a.sort(() => -1);

console.log(reverse([undefined, 0]));
console.log(reverse([0, undefined]));

I don’t quite understand how it works behind the scene, after all I am not even comparing anything, just return -1 to reverse it. Any ideas about this behavior?