Is there a better way of writing this If statement?

I was working on a JavaScript program, and needed an if statement to assign a value to a variable when a is larger than b.

if (a > b) {
  var c = 11;
} 

Is there a better way of doing this?

Originally I thought of using a conditional operator:

(a > b) ? c : 11

But when I log c to console, it retunes undefined.
I would really appreciate any help/advice on this.

Develop on two computers

I have a computer at home (main) and a notebook (secondary). When I leave the house I like to program on my laptop. I would like to know if anyone knows any way that, when I save my file/progress (on the primary computer/even on the secondary), it is possible to continue where I left off previously. I don’t need to upload it every time I’m doing it, using Google Drive.

I currently use Google Drive to upload from one computer and download from another. However, I would like it to be automatic in some way. No need to upload or download.

Laravel Livewire input fields not passing using postal code / address search api

In my laravel 10 with livewire ecommerce project, i am using postal code api to search and fill the address fields in the checkout page. Upon clicking to checkout after filling in the form, the validation process starts. Even though they have been filled using the api, the fields arent recognized and gives message to fill them. Only after manually clicking the fields and type something out, the data is then validated.

Api is called upon function sample6_execDaumPostcode(), and uses javascript to open a popup page where user can search for their address, and afterwards the fields are automatically inserted.

Here is my livewire checkout component =

<?php

namespace AppLivewireFrontendCheckout;

use AppModelsCart;
use AppModelsOrder;
use LivewireComponent;
use AppModelsOrderitem;
use IlluminateSupportStr;

class CheckoutShow extends Component
{
    public $carts, $totalProductAmount = 0;

    public $fullname, $email, $phone, $pincode, $address, $secondAddress, $thirdAddress, $payment_mode = NULL, $payment_id = NULL;

    public function rules()
    {
        return [
            'fullname' => 'required|string|max:121',
            'email' => 'required|email|max:121',
            'phone' => 'required|string|max:11|min:9',
            'pincode' => 'required|string|max:5|min:5',
            'address' => 'required|string|max:500',
            'secondAddress' => 'required|string|max:500',
            'thirdAddress' => 'nullable|string|max:500'
        ];
    }

Here is the livewire page view input fields =

 <div class="col-md-6 mb-3">
                                <label>우편번호</label>
                                <input type="text" wire:model="pincode" class="form-control" id="sample6_postcode" placeholder="우편번호">
                                @error('pincode') <small class="text-danger">{{ $message }}</small> @enderror
                            </div>
                            <div class="col-md-6">
                                <input class="btn btn1" type="button" onclick="sample6_execDaumPostcode()" value="우편번호 찾기">
                            </div>
                            <div class="col-md-12 mb-3">
                                <label>주소</label>
                                <textarea type="text" wire:model="address" class="form-control" id="sample6_address" placeholder="주소" rows="2"></textarea>
                                @error('address') <small class="text-danger">{{ $message }}</small> @enderror
                            </div>
                            <div class="col-md-12 mb-3">
                                <label>상세주소</label>
                                <input type="text" wire:model="secondAddress" class="form-control" id="sample6_detailAddress" placeholder="상세주소">
                                @error('secondAddress') <small class="text-danger">{{ $message }}</small> @enderror
                            </div>
                            <div class="col-md-12 mb-3">
                                <label>참고항목</label>
                                <input type="text" wire:model="thirdAddress" class="form-control" id="sample6_extraAddress" placeholder="참고항목">
                            </div>

Issue with Path Aliasing using “imports” in package.json – Error [ERR_MODULE_NOT_FOUND]

I am facing difficulties implementing path aliasing using the imports field in the package.json file. Despite my efforts, I keep encountering the following error:

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:server-tssrcmessagesmessages.router' imported from C:server-tsdistindex.js

directory structure

|   .env
|   .eslintignore
|   .eslintrc.js
|   .prettierrc.js
|   package-lock.json
|   package.json
|   tree.txt
|   tsconfig.json
|   
+---dist
|   |   index.js
|   |   index.js.map
|   |   
|   +---messages
|   |       messages.router.js
|   |       messages.router.js.map
|   |       messages.service.js
|   |       messages.service.js.map
|   |       
|   ---middleware
|           auth0.middleware.js
|           auth0.middleware.js.map
|           
+---node_modules
|           
---src
    |   index.ts
    |   
    +---messages
    |       messages.router.ts
    |       messages.service.ts
    |       
    +---middleware
    |       auth0.middleware.ts
    |       
    ---types
            process-env.d.ts

package.json

{
...
  "main": "src/index.ts",
  "type": "module",
  "scripts": {
    "start": "tsx src/index.ts",
    "dev": "tsx watch src",
        "start-node": "node dist/index.js",
    "lint": "eslint src/**/*.ts --fix",
    "build": "tsc"
  },
    "imports": {
    "##/*": "./src/*"
    },
...
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "lib": ["ES2023"],
    "module": "ESNext",
    "moduleResolution": "Node",
    "baseUrl": "./",
    "paths": {
      "##/*": ["./src/*"]
    },
    "outDir": "dist/",
    "removeComments": true,
    "sourceMap": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

index.ts

...
import { messagesRouter } from '##/messages/messages.router';
...
  • I have ensured that my TypeScript compiler version is compatible with the ECMAScript module system.
  • The baseUrl and paths configurations in tsconfig.json are set up correctly, as far as I can tell.
  • The paths seem correct, but the runtime is unable to locate the module.

What could be causing the “Error [ERR_MODULE_NOT_FOUND]” when trying to use path aliases with the imports field in package.json? Any suggestions on how to resolve this issue would be greatly appreciated.

Thank you in advance!

Please help a beginner. NestJS + React on Vite + turbo. Problem with MongoDB

This is my first time using the forum, so if anything is wrong please let me know. Temporarily, I don’t know much about frameworks related to JavaScript + TypeScript, and I don’t know the languages themselves very well. Stack: NestJS + React on Vite + turbo.

After installing @nestjs/server-static in NestJS and running turbo when merging, my database on Mongoose MongoDB sends an error:
ERROR [MongooseModule] Unable to connect to the database. Retrying (…).

Separately, when NestJS is running, the Mongoose MongoDB database finds and works, but in the overall site build in turbo it does not work. What to do?

MONGODB_URI='mongodb://mongodb:2023@localhost:27017/whatsapp?authSource=admin&directConnection=true'

I don’t know if the code is needed. If you need it I can send it.

I need to have a site on a NestJS server where the entire stack runs on a single URL, like http://localhost:3000.

Handling PWA Installations on Browsers Without BeforeInstallPrompt: Seeking Alternatives

I’m developing a Progressive Web App (PWA) that exhibits expected behavior on Chrome, where the installation prompt is triggered using the BeforeInstallPrompt event.

On browsers like Firefox and Mi Browser, which lack support for this event (verified on CanIUse), no prompt should be shown.
Intriguingly, web.dev manages to display a prompt on these browsers despite the absence of the event.
Firefox Prompt Mi Browser Prompt

Question:

How can web.dev PWA work on browsers like Firefox and Mi Browser without the BeforeInstallPrompt? Are there alternative methods or best practices for handling PWA installations on browsers without BeforeInstallPrompt event support?

Additional Context:

  • Application built with Vue.js.
  • Service Worker is automatically generated by the VitePWA plugin.
  • PWA functions correctly on supported browsers (e.g., Chrome and Edge).
  • Testing on Firefox and Mi Browser reveals no BeforeInstallationPrompt event triggering.

Environment:

  • Browsers: Chrome, Firefox, Mi Browser
  • Operating System: Android

Any insights or guidance on alternative methods for managing PWA installations on browsers without BeforeInstallPrompt support would be highly appreciated. Thank you!

What I Expected to Happen:

  • On Chrome: Expecting the installation prompt to be displayed via the BeforeInstallPrompt event.
  • On Firefox and Mi Browser: Expecting no installation prompt due to the absence of support for the BeforeInstallPrompt event.

What Resulted:

Upon testing on Firefox and Mi Browser, there was no triggering of the BeforeInstallPrompt event, as expected. However, I noticed that web.dev manages to display a prompt on these browsers, even though they theoretically lack support for the BeforeInstallPrompt event.

Leaflet MarkerClusterMap exhibits weird behavior, nodes only get added to map

I am trying to create a map from bikeTheftMapDataByYear data that looks like this.

{2019: "E-Scooters": [datapoints... 
     : Bikes: [datapoints...
      : "E-Bikes": [datapoints...
,
2020: "E-Scooter": 
...
}

For some reason, whenever I change the year/vehicle type the map does not change correctly. The number of markers only increases; I think the map for some reason is not “clearing” previous markers. Does anyone have any ideas why this is happening?


function MarkerClusterMap() {
  const [vehicleType, setVehicleType] = React.useState({
    name: 'Bikes',
  });

  const [year, setYear] = React.useState({
    name: 'all',
  });

  const handleVehicleChange = (event) => {
    const { value } = event.target;
    setVehicleType({
      name: value,
    });
  };

  const handleYearChange = (event) => {
    const { value } = event.target;
    setYear({
      name: value,
    });
  };

  return (
    <div>
      <div>
      <FormControl className={classes.formControl}>
        <InputLabel>Select vehicle</InputLabel>
        <Select
          value={vehicleType.name}
          id="regionSelector"
          name="region"
          onChange={handleVehicleChange}
          defaultValue="E-Scooters"
        >
          <MenuItem value="E-Scooters">E-Scooters</MenuItem>
          <MenuItem value="Bikes">Bikes</MenuItem>
          <MenuItem value="E-Bikes">E-Bikes</MenuItem>
        </Select>
      </FormControl>

      <FormControl className={classes.formControl}>
        <InputLabel>Select year</InputLabel>
        <Select
          value={year.name}
          id="regionSelector"
          name="region"
          onChange={handleYearChange}
          defaultValue="all"
        >
          <MenuItem value="2019">2019</MenuItem>
          <MenuItem value="2020">2020</MenuItem>
          <MenuItem value="2021">2021</MenuItem>
          <MenuItem value="2022">2022</MenuItem>
          <MenuItem value="2023">2023</MenuItem>
          <MenuItem value="all">all</MenuItem>
        </Select>
      </FormControl>

      {(typeof window !== 'undefined') ? ( // must condition inside of a div in case content is null

        <MapContainer>
          <TileLayer url="https://{s}.basemaps.cartocdn.com/rastertiles/voyager_labels_under/{z}/{x}/{y}.png" />

          <MarkerClusterGroup>
            {bikeTheftMapDataByYear[year.name][vehicleType.name].map((info) => (
              <Marker
                position={[info.center[0], info.center[1]]}
                key={info.k}
                icon={createIcon(vehicleType.name, 20)}
              >
                <Popup>{info.Location}</Popup>
              </Marker>
        </MapContainer>

      ) : <p> Map is loading... </p>}
    </div>

  );
}

export default MarkerClusterMap;

Available points for playing monkey

There is a monkey which can walk around on a planar grid. The monkey can move one space at a time left, right, up or down. That is, from (x, y) the monkey can go to (x+1, y), (x-1, y), (x, y+1), and (x, y-1).

Points where the sum of the digits of the absolute value of the x coordinate plus the sum of the digits of the absolute value of the y coordinate are lesser than or equal to n are accessible to the monkey. For example, the point (59, 79) is inaccessible because 5 + 9 + 7 + 9 = 30, which is greater than n. Another example: the point (-5, -7) is accessible because abs(-5) + abs(-7) = 5 + 7 = 12, which is less than n.

How many points can the monkey access if it starts at (0, 0), including (0, 0) itself?

Input sample:

There is no input for this program.

Output sample:

Print the number of points the monkey can access. It should be printed as an integer — for example, if the number of points is 10, print “10”, not “10.0” or “10.00”, et

I used JavaScript like below.

const monkeyPlay = (sum) => {
  const availablePoints = [{ x: 0, y: 0 }];
  const result = [];

  const checkAvailable = (point) => {
    if (!exist(result, point) && getSum(point.x) + getSum(point.y) <= sum) {
      result.push(point);
      availablePoints.push(
        { x: point.x + 1, y: point.y },
        { x: point.x, y: point.y + 1 },
        { x: point.x - 1, y: point.y },
        { x: point.x, y: point.y - 1 }
      );
    }
  };

  while (availablePoints.length != 0) {
    checkAvailable(availablePoints.pop());
  }
  return result;
};

console.log(monkeyPlay(19));

It works correctly but takes too long time when n>=19.

I’ll be appreciated of any help.

Thanks.

Why are the first dots only half dots and how to fix

I’m having an issue where the first and last dots are cut in half essentially. I’ve tried rewriting the JavaScript and it still does not work. Can I get some insight?

HTML/JS

            <div class="grid-item grid-layout4">
                <canvas id="myJourney" width="1000" height="100"></canvas>
            </div>
            <script>
     // Get the canvas element and context
     var canvas = document.getElementById('myJourney'); // Corrected canvas ID
    var ctx = canvas.getContext('2d');

    // Sample data for the line chart
    var data = [10, 30, 20, 50, 40, 60];

    // Function to draw the line chart
    function drawLineChart() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        for (var i = 0; i < data.length; i++) {
            var x = i * (canvas.width / (data.length - 1));
            var y = canvas.height - data[i];

            // Draw a small circle at each data point
            ctx.beginPath();
            ctx.arc(x, y, 5, 0, 2 * Math.PI);
            ctx.fillStyle = 'blue';
            ctx.fill();

            // Draw a line to the next point
            if (i < data.length - 1) {
                var nextX = (i + 1) * (canvas.width / (data.length - 1));
                var nextY = canvas.height - data[i + 1];

                ctx.beginPath();
                ctx.moveTo(x, y);
                ctx.lineTo(nextX, nextY);
                ctx.strokeStyle = 'blue';
                ctx.lineWidth = 2;
                ctx.stroke();
            }
        }
    }

    // Function to handle mousemove event
    function handleMouseMove(event) {
        var mouseX = event.clientX - canvas.getBoundingClientRect().left;
        var mouseY = event.clientY - canvas.getBoundingClientRect().top;

        // Check if the mouse is over any point
        for (var i = 0; i < data.length; i++) {
            var x = i * (canvas.width / (data.length - 1));
            var y = canvas.height - data[i];

            // Check if the mouse is over the point
            if (Math.sqrt(Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2)) < 5) {
                // Draw a larger dot or perform any other action for hover effect
                ctx.beginPath();
                ctx.arc(x, y, 8, 0, 2 * Math.PI);
                ctx.fillStyle = 'red';
                ctx.fill();
            }
        }
    }

    // Attach the mousemove event handler to the canvas
    canvas.addEventListener('mousemove', handleMouseMove);

    // Initial drawing of the line chart
    drawLineChart();
            </script>
        </div>
    </div>

I’ve tried using ChatGPT 4 and I was unable to get any answers to why only half is appearing. This is my first time making a line chart in HTMl so any insight would be helpful.

How to fix/debug this particular (and preferably in general) TypeScript compilation error?

I have this TypeScript code (it’s dirty, with comments because I decided to leave them to show various approaches I’ve tried):

function getPlacesToStopExchange(): {
  our: { i: number; val: number; }[];
  enemy: { i: number; val: number; }[];
  //[party in 'our' | 'enemy' ]: { i: number; val: number; }[];
} {
  return valuesByMoves.reduce((o, v, i) => {
    if (i === 0 || i % 2) {
      //  //we move
      const el: { i: number; val: number; } = { i, val: v, };
      o.enemy.push(el);
    } else {
    //  o.our.push({ i, val: v, } as { i: number; val: number; }));
    }
    return o;
  }, { enemy: [], our: [], });
}

On line 10: o.enemy.push(el); I’m getting this error:

error TS2345: Argument of type '{ i: number; val: number; }' is not assignable
to parameter of type 'never'.

134           o.enemy.push(el);

If I comment that line — no error is present, so I’m pretty sure it’s there exactly, not on the type declaration of the function’s return value or the reduce initial value.

Does anyone know how to solve this? I’ve seen other questions on SO which say virtually, that I have to specify the type in the place the error is occurring, but as one can see I’ve tried this in many ways.

Also I tried to look into the tsc code, but there is no call stack no nothing. So I don’t know where to look.

So if someone provided a general advise on how to debug tsc errors, I’d be very grateful.

Thank you.

React loader on children router

I have a App.js file that includes all the routes that I have. I wanted to make use of react router data loader.

import React from 'react'
import { Routes, Route, Navigate, RouterProvider, createBrowserRouter, createRoutesFromElements} from 'react-router-dom'

import { ThemeProvider, CssBaseline } from '@mui/material'

import Login from './pages/global/Login'
import NoSidebarLayout from './pages/global/NoSidebarLayout'
import SidebarLayout from './pages/global/SidebarLayout'

import NotFound from './pages/NotFound'
import ComingSoon from './pages/ComingSoon'
import Home from './pages/Home'
import About from './pages/About'
import Contact from './pages/Contact'
import ItemRoutes from './pages/ItemRoutes'
import CountryRoutes from './pages/country/CountryRoutes'
import PortRoutes from './pages/port/PortRoutes';
import ServicesManagerRoutes from './pages/serviceManager/ServicesManagerRoutes';
import ChargeManagerRoutes from  './pages/chargeManager/ChargeManagerRoutes';
import PortChargesRoutes from './pages/portCharges/PortChargesRoutes';
import PortsRoutes from './pages/ports/PortsRoutes';

import PrivateRoutes from './components/PrivateRoutes';
import { ColorModeContext, useAppTheme } from './theme'

import { Provider } from "react-redux";
import store from "./redux/store";

import CountryList, {loader as CountryListLoader} from './pages/country/CountryList';
import Country from './pages/country/Country'

const router = createBrowserRouter(createRoutesFromElements(
  <Route>
    <Route element={<PrivateRoutes />} >
      <Route element={<SidebarLayout />} >
        <Route path="/ui/" element={<Home />} />
        <Route path="/ui/items/*" element={<ItemRoutes />} />
        <Route path="/ui/countries/*" element={<CountryRoutes />}/>
        <Route path="/ui/ports/*" element={<PortRoutes />} />
        <Route path="/ui/contact" element={<Contact />} />
        <Route path="/ui/about" element={<About />} />
        <Route path="/ui/service-manager/*" element={<ServicesManagerRoutes />} />
        <Route path="/ui/charge-manager/*" element={<ChargeManagerRoutes />} />
        <Route path="/ui/port-charges/*" element={<PortChargesRoutes />} />
        <Route path="/ui/port-manager/*" element={<PortsRoutes />} />
        <Route path="/ui/coming-soon/*" element={<ComingSoon />} />
        <Route path="*" element={<NotFound />} />
      </Route>
    </Route>
    <Route element={<NoSidebarLayout />}>
      <Route path="/ui/login" element={<Login/>}  />
      <Route path="*" element={<NotFound />} />
    </Route>
  </Route>
))

const App = () => {
    const [theme, colorMode] = useAppTheme();

    return (
      <Provider store={store}>
        <ColorModeContext.Provider value={colorMode}>
            <ThemeProvider theme={theme}>
                <CssBaseline />
                <div className="app">
                    <RouterProvider router={router}/>
                </div>
            </ThemeProvider>
        </ColorModeContext.Provider>
      </Provider>
    )
}


export default App

on the CountryRoutes I have this,which includes the loader

import React from 'react'
// import { Routes, Route } from 'react-router-dom';
import { Routes, Route, Navigate, RouterProvider, createBrowserRouter, createRoutesFromElements} from 'react-router-dom'

import CountryList , {loader as CountryListLoader} from './CountryList';
import Country from './Country';


const CountryRoutes = () => (
  <Routes>
    <Route >
      <Route index element={<CountryList />} loader={CountryListLoader} />
      <Route path=":id" element={<Country />} />
    </Route>
  </Routes>
);

export default CountryRoutes;

With this setup the loader is not working but when I directly add the children routes to the parent like this,

const router = createBrowserRouter(createRoutesFromElements(
  <Route>
    <Route element={<PrivateRoutes />} >
      <Route element={<SidebarLayout />} >
        <Route path="/ui/" element={<Home />} />
        <Route path="/ui/items/*" element={<ItemRoutes />} />
        <Route path="/ui/countries/*">
          {/* Directly adding the children routes  */}
          <Route index element={<CountryList />} loader={CountryListLoader} />
          <Route path=":id" element={<Country />} />
        </Route>
        <Route path="/ui/ports/*" element={<PortRoutes />} />
        <Route path="/ui/contact" element={<Contact />} />
        <Route path="/ui/about" element={<About />} />
        <Route path="/ui/service-manager/*" element={<ServicesManagerRoutes />} />
        <Route path="/ui/charge-manager/*" element={<ChargeManagerRoutes />} />
        <Route path="/ui/port-charges/*" element={<PortChargesRoutes />} />
        <Route path="/ui/port-manager/*" element={<PortsRoutes />} />
        <Route path="/ui/coming-soon/*" element={<ComingSoon />} />
        <Route path="*" element={<NotFound />} />
      </Route>
    </Route>
    <Route element={<NoSidebarLayout />}>
      <Route path="/ui/login" element={<Login/>}  />
      <Route path="*" element={<NotFound />} />
    </Route>
  </Route>
))

Notice that I directly added the children route to the /ui/countries/* . I am a bit confused to which router should I add the loader.

document.domain mutation is ignored because the surrounding agent cluster is origin-keyed

  let elementList = [];
  const query = 'body > div:nth-child(2) > div:nth-child(2) > div > div > div:nth-child(2) > div > div:nth-child(1) > ol > li:nth-child(n) > div.cart--basket_body > div > ul > li > div > div.item_info > dl > dd > div.section.item_title > a > span';
  const itemList = document.querySelectorAll(query);
  itemList.forEach((item) => {
    elementList.push(item.textContent); 
  });
  console.log(elementList);

if I have ‘document.domain mutation is ignored because the surrounding agent cluster is origin-keyed.’ error, does this mean i cannot retrieve the data from the html element page?

javascript not accessing array or object

I’m working on a script that will loop through something similar to the following

$( document ).ready(function() {

  let myObj = {};

  initLoop();

  function initLoop() { //this loads the initial frames into the object
    $('.looper').each(function(i, e){
      var attr1 = $(this).attr('attr1');
      var attr2 = $(this).attr('attr2');
      var attr3 = $(this).attr('attr3');
      var contents = $(this).html();
      myObj[attr1][attr2][attr3] = contents;
    });
  }
});

I’m looping through a set of divs structured like this…

<div class="looper" attr1="1" attr2="1" attr3="1">content</div>
<div class="looper" attr1="1" attr2="1" attr3="2">content</div>
<div class="looper" attr1="1" attr2="1" attr3="3">content</div>
<div class="looper" attr1="1" attr2="2" attr3="1">content</div>
<div class="looper" attr1="1" attr2="2" attr3="2">content</div>
<div class="looper" attr1="1" attr2="2" attr3="3">content</div>
<div class="looper" attr1="1" attr2="3" attr3="1">content</div>
<div class="looper" attr1="1" attr2="3" attr3="2">content</div>
<div class="looper" attr1="1" attr2="3" attr3="3">content</div>

I’m getting the error

jQuery.Deferred exception: Cannot read properties of undefined (reading ‘1’) TypeError: Cannot read properties of undefined (reading ‘1’)

I’m a bit lost on why this isn’t working.
Can anyone suggest any changes?

I need to console.log a variable and in the same line run a function then also print the variable again

Basically, I have a variable, c1, which is given a random hex value. Then, I need to print it to the console. But, then, I want to print another hex value, and I don’t want to make another variable (because i’m lazy), and so instead, I want to do something like this:

function thing() {
  // generate random hex value code (it works)
}

console.log (variable + thing() + variable);

I have not found anything that could help with this, and I don’t even know if what I’m trying to do is possible. If it isn’t, then I will add the other variables, but I want to try with this first.

I don’t even know what to try first, and so here I am!