Javascript function returns from function right after await statement

I am writing client-side javascript functions to send post request to server and to get result. I am using such resources in my work:

  1. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
  2. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
  3. How do I resolve additional post request in onSubmit method in React (I do not use react, just regular javascript. Answers there mention async-await mechanism which helps you to avoid spinning callbacks).

Here is my code:

Html part – button that triggers Javascript:

<button class="btn btn-success greenbtn" id="btnFinishDay" onclick="btnFinishDay_click(event)" name="btnFinishDay" >GO</button></div>

Here is button handler:

async function btnFinishDay_click(eee) {
    var txtBarCodeValue = document.getElementById("txtBarCode").value;
    var rrr = await postAjaxWithFetch('/CheckItem', { barcodeValue: txtBarCodeValue });
    console.log(rrr);
    alert("CheckCustomer request was sent");
}

Here is how I send post request:

/*
A modern way to use POST request with form data and ajax. 
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
*/
async function postAjaxWithFetch(url, data) {
    // if data is string then use it as is. If it is Object then generate formdata string from it
    var params = typeof data == 'string' ? data : Object.keys(data).map(
        function (k) { return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }
    ).join('&');
    const request1 = new Request(url, {
        method: "POST",
        body: params,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    });
    const response1 = await fetch(request1);
    console.log(response1);
    alert("hello from postAjaxWithFetch")
    return response1;
}

unfortunately right after statement with await is reached then subroutine quits. In debugger I see:

  1. btnFinishDay_click is entered
  2. await postAjaxWithFetch call is reached
  3. postAjaxWithFetch function is entered
  4. const response1 = await fetch(request1) is reached
  5. postAjaxWithFetch is stepped out, no console.log and no alert is called
  6. Network monitor does not show any /CheckItem request
  7. btnFinishDay_click finishes, no alert is shown

To sum it up – no alert calls are processed. And this feels confusing for me…

Question is: Why does async and await in regular javascript act like this disrupting normal flow?

Vue router with nested components

How can I make the base path “/” redirect to the address BASE_PATHS.FIRE and from it there is a redirect to the address BASE_PATHS.FIRE + FIRE.JUPI. The page stops at the address “sitename.com//fire-safety/” and does not go to the address “sitename.com//fire-safety/jupi”

const BASE_PATHS = {
  FIRE: "/fire-safety/",
}

const PURVIEWS = {
  FIRE: {title: translate('name')},
}
export const FIRE = {
  SELF: `fire-safety`,
  JUPI: `jupi`,
  EMP: `emp`,
  VISION: `vision`,
}

const routes = [
  {
    path: '/',
    redirect: BASE_PATHS.FIRE,
    component: () => import('Layout.vue'),
  },

  {
    path: BASE_PATHS.FIRE,
    redirect: BASE_PATHS.FIRE + FIRE.JUPI,
    component: () => import('Layout.vue'),
    children: [
      {
        name: FIRE.SELF,
        path: BASE_PATHS.FIRE,
        children: [
          {
            name: FIRE.JUPI,
            path: FIRE.JUPI,
            component: () => import('jupi.vue'),
            meta: {
              breadcrumbs: [
                PURVIEWS.FIRE,
                {title: translate('name1')},
              ]
            },
          },
          {
            path: FIRE.EMP,
            name: FIRE.EMP,
            component: () => import('emp.vue'),
            meta: {
              breadcrumbs: [
                PURVIEWS.FIRE,
                {title: translate('name2')},
              ]
            }
          },
          {
            path: FIRE.VISION,
            name: FIRE.VISION,
            component: () => import('vision.vue'),
            meta: {
              breadcrumbs: [
                PURVIEWS.FIRE,
                {title: translate('name3')},
              ]
            }
          },
        ]
      },

    ]
  }
]

export default routes;

I tried to directly translate the address from “/” to BASE_PATHS.FIRE + FIRE.JUPI but then when accidentally going to the address “sitename.com//fire-safety/” everything remains the same

How to recompile a project developed with an old version of Expo sdk today (2024)?

I got a copy of the original code developed using react native and the “suspected” expo SDK 37.0.7. I want to recompile and enable this code. Is this possible? I am new to RN, can anyone tell me how to get started? Thank you very much! !

  "dependencies": {
    "@react-native-community/async-storage": "^1.11.0",
    "@react-native-community/datetimepicker": "^4.0.0",
    "@react-native-community/masked-view": "^0.1.10",
    "@react-native-community/progress-bar-android": "^1.0.3",
    "@react-native-community/progress-view": "^1.2.2",
    "@react-native-community/toolbar-android": "^0.1.0-rc.2",
    "@react-native-firebase/app": "^11.5.0",
    "@react-native-firebase/auth": "^11.5.0",
    "@react-native-firebase/messaging": "^11.5.0",
    "apollo-boost": "^0.4.9",
    "apollo-cache-inmemory": "^1.6.6",
    "apollo-link-http": "^1.5.17",
    "expo": "~37.0.7",
    "graphql": "^15.3.0",
    "graphql-tag": "^2.11.0",
    "immutable": "^4.0.0",
    "intl": "^1.2.5",
    "moment": "^2.24.0",
    "react": "~16.12.0",
    "react-apollo": "^3.1.5",
    "react-dom": "~16.12.0",
    "react-intl": "^5.13.2",
    "react-native": "~0.63.5",
    "react-native-animated-splash-screen": "^2.0.5",
    "react-native-autocomplete-input": "^4.2.0",
    "react-native-base64": "^0.1.0",
    "react-native-camera": "^3.43.6",
    "react-native-datepicker": "^1.7.2",
    "react-native-device-info": "^7.2.1",
    "react-native-dropdown-picker": "^3.6.8",
    "react-native-fs": "^2.16.6",
    "react-native-geocoding": "^0.4.0",
    "react-native-geolocation-service": "^5.0.0",
    "react-native-gesture-handler": "~1.5.0",
    "react-native-image-picker": "^3.1.1",
    "react-native-image-zoom-viewer": "^3.0.1",
    "react-native-indicators": "^0.17.0",
    "react-native-keyboard-accessory": "^0.1.16",
    "react-native-linear-gradient": "^2.5.6",
    "react-native-maps": "^0.30.2",
    "react-native-markdown-display": "^6.1.6",
    "react-native-modal-datetime-picker": "^13.0.0",
    "react-native-modal-dropdown": "^0.7.0",
    "react-native-paper": "4.1.0",
    "react-native-pdf": "~6.3.0",
    "react-native-permissions": "^3.0.3",
    "react-native-popover-view": "^2.1.3",
    "react-native-reanimated": "^1.9.0",
    "react-native-render-html": "^4.2.3",
    "react-native-restart": "^0.0.17",
    "react-native-safe-area-context": "^2.0.0",
    "react-native-screens": "2.0.0-alpha.12",
    "react-native-select-input-ios": "^2.0.5",
    "react-native-snackbar-reddit": "^0.0.8",
    "react-native-splash-screen": "^3.2.0",
    "react-native-switch-selector": "^2.0.6",
    "react-native-tab-view": "^2.15.2",
    "react-native-text-ticker": "^1.14.0",
    "react-native-unimodules": "~0.7.0",
    "react-native-vector-icons": "^6.6.0",
    "react-native-version-check": "^3.4.2",
    "react-native-web": "~0.11.7",
    "react-native-webview": "^11.23.1",
    "react-navigation": "^4.3.9",
    "react-navigation-drawer": "^2.4.13",
    "react-navigation-stack": "^2.8.2",
    "react-navigation-tabs": "^2.9.0",
    "react-redux": "^7.1.1",
    "recompose": "^0.30.0",
    "redux": "^4.0.4",
    "redux-immutable": "^4.0.0",
    "redux-thunk": "^2.3.0",
    "rn-fetch-blob": "^0.12.0",
    "rn-maps-polyline": "^2.0.0",
    "styled-components": "^5.1.1",
    "with-immutable-props-to-js": "^1.0.2"

I have tried to install the expo module, but the installation is the new version 51.0.32, and there are many errors in the process, so I am thinking whether I should first use expo 37.0.7 (specified in the project app.json file) After the original code can run normally, continue to update to the latest version of the sdk.

I also tested according to the following discussion thread, but the discussion explained how to recommend an empty old version of the development environment, but what I got was an existing project
Create an expo project with a specific version

JavaScript id details are showing one result irrespective of the id

I am creating a book app using javascript using NY Times api where users can view the book details by clicking any of the book. I have given each book a different id using primary_isbn10 from the api. The problem is that if I click on any book, it shows only one book details in the detals.html page. It doesn’t matter which book I have clicked; the results are not changing and only one particular book details are showing.

Here is the code

index.html

   <div class="container-fluid p-5 bg-danger text-white text-center">
    <!-- <h1>My First Bootstrap Page</h1> -->
    <p>Search any book!</p> 
    <div id="searchBox" class="mobile-form">
        <form action="/search" class="search-form" id="searchform" method="get">
            <span id="noEasy"><input class="sb-search-submit" type="submit" value="">
    <span class="sb-icon-search"></span></span>
            <input id="sbox" name="q" placeholder="To search type + hit enter" type="text" x-webkit-speech="">
        </form>
    </div>
  </div>
  <div class="container bg-white">
    <nav class="navbar navbar-expand-md navbar-light bg-white">
        <div class="container-fluid p-0"> <a class="navbar-brand text-uppercase fw-800" href="#"><span class="border-red pe-2">New</span>Product</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#myNav" aria-controls="myNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="fas fa-bars"></span> </button>
            <div class="collapse navbar-collapse" id="myNav">
                <div class="navbar-nav ms-auto"> <a class="nav-link active" aria-current="page" href="#">Best Seller</a> <a class="nav-link" href="#">Women's</a> <a class="nav-link" href="#">Men's</a> <a class="nav-link" href="#">Kid's</a> <a class="nav-link" href="#">Accessories</a> <a class="nav-link" href="#">Cosmetics</a> </div>
            </div>
        </div>
    </nav>
    <div class="row currentbooks">
    </div>
    
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="js/script.js"></script>
<script src="js/details.js"></script>

details.html

<div class="container my-5">
    <div class="row details-snippet1">
        <div class="col-md-7">
            <div class="row">
                <div class="col-md-2 mini-preview">
                    <img class="img-fluid" src="https://cdn.pixabay.com/photo/2015/07/24/18/40/model-858754_960_720.jpg" alt="Preview">
                    <img class="img-fluid" src="https://cdn.pixabay.com/photo/2015/07/24/18/38/model-858749_960_720.jpg" alt="Preview">
                    <img class="img-fluid" src="https://cdn.pixabay.com/photo/2015/07/24/18/39/model-858751_960_720.jpg" alt="Preview">
                    <img class="img-fluid" src="https://cdn.pixabay.com/photo/2015/07/24/18/37/model-858748_960_720.jpg" alt="Preview">
                </div>
                <div class="col-md-10">
                    <div class="product-image">
                        
                    </div>

                </div>
            </div>

        </div>
        <div class="col-md-5">
            <div class="category"><span class="theme-text">Category:</span> Women</div>
            <div class="title">Black Dress For Women</div>
            <div class="ratings my-2">
                <div class="stars d-flex">
                    <div class="theme-text mr-2">Product Ratings: </div>
                    <div>&#9733;</div>
                    <div>&#9733;</div>
                    <div>&#9733;</div>
                    <div>&#9733;</div>
                    <div>&#9733;</div>
                    <div class="ml-2">(4.5) 50 Reviews</div>
                </div>
            </div>
            <div class="price my-2">$100.00 <strike class="original-price">$120.00</strike></div>
            <div class="theme-text subtitle"><b>Brief Description:</b></div>
            <div class="brief-description">
                Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad dicta reiciendis odio consequuntur sunt magnam eum facilis quaerat dolor aperiam labore facere amet officiis, unde quae distinctio earum culpa omnis soluta voluptate tempora placeat?.
            </div>


            <hr>
            <div class="row">
                <div class="col-md-3">
                    <input type="number" class="form-control" value="1">
                </div>
                <div class="col-md-9"><button class="btn addBtn btn-block">Add to basket</button></div>
            </div>

        </div>
    </div>

    <div class="additional-details my-5 text-center">
        <!-- Nav pills -->
        <ul class="nav nav-tabs justify-content-center">
            <li class="nav-tabs">
                <a class="nav-link active" data-toggle="tab" data-bs-toggle="tab" href="#home">Description</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-toggle="tab" data-bs-toggle="tab" href="#menu1">Reviews</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-toggle="tab" data-bs-toggle="tab" href="#menu2">Specifications</a>
            </li>
        </ul>

        <!-- Tab panes -->
        <div class="tab-content mt-4 mb-3">
            <div class="tab-pane container active" id="home">
                <div class="description">
                    Lorem ipsum dolor sit, amet consectetur adipisicing elit. Provident magni assumenda consectetur facere eius. Minus reprehenderit placeat ullam vel ab eaque sequi impedit, ipsum soluta temporibus fugit ipsa. Dolor libero modi molestiae dicta, vitae minus laborum error cum consequatur autem minima eveniet porro obcaecati quibusdam possimus eos, debitis sint magnam, explicabo accusantium aspernatur ipsa repellat tempore nihil. Cum placeat voluptate dignissimos dicta harum consectetur, nemo debitis tempore. Quod culpa perspiciatis unde natus. Modi expedita, ab repellendus reiciendis sed voluptate, culpa laborum ad, consectetur quas tempora quo? Quibusdam doloribus magnam maxime, accusamus officiis odit reiciendis labore laudantium. Molestiae corporis temporibus ad?
                </div>
            </div>
            <div class="tab-pane container fade" id="menu1">
                <div class="review">
                    <p>PUT REVIEWS DESIGN HERE</p>
                </div>
            </div>
            <div class="tab-pane container fade" id="menu2">
                <div class="specification">
                    <p>PUT SPECIFICATIONS HERE</p>
                </div>
            </div>
        </div>
    </div>



    <div class="related-products details-snippet1">

        <div class="related-heading theme-text">Related Products</div>

        <div class="row">

                            <div class="col-md-3">
                    <div class="related-product">
                        <img class="img-fluid" src="https://source.unsplash.com/gsKdPcIyeGg" alt="Related Product">
                    </div>
                    <div class="related-title">Lovely Black Dress</div>
                    <div class="d-flex">
                        <div class="related-price mr-auto">$100.00</div>
                        <div class="stars d-flex">
                            <div>&#9733;</div>
                            <div>&#9733;</div>
                            <div>&#9733;</div>
                            <div>&#9733;</div>
                            <div>&#9733;</div>
                        </div>
                    </div>
                </div>
                            <div class="col-md-3">
                    <div class="related-product">
                        <img class="img-fluid" src="https://source.unsplash.com/sg_gRhbYXhc" alt="">
                    </div>
                    <div class="related-title">Lovely Dress With Patterns</div>
                    <div class="d-flex">
                        <div class="related-price mr-auto">$1199.00</div>
                        <div class="stars d-flex">
                            <div>&#9733;</div>
                            <div>&#9733;</div>
                            <div>&#9733;</div>
                            <div>&#9733;</div>
                            <div>&#9733;</div>
                        </div>
                    </div>
                </div>
                            <div class="col-md-3">
                    <div class="related-product">
                        <img class="img-fluid" src="https://source.unsplash.com/gJZQcirK8aw" alt="">
                    </div>
                    <div class="related-title">Lovely Fashion Dress</div>
                    <div class="d-flex">
                        <div class="related-price mr-auto">$200.00</div>
                        <div class="stars d-flex">
                            <div>&#9733;</div>
                            <div>&#9733;</div>
                            <div>&#9733;</div>
                            <div>&#9733;</div>
                            <div>&#9733;</div>
                        </div>
                    </div>
                </div>
                            <div class="col-md-3">
                    <div class="related-product">
                        <img class="img-fluid" src="https://source.unsplash.com/qbB_Z2pXLEU" alt="">
                    </div>
                    <div class="related-title">Lovely Red Dress</div>
                    <div class="d-flex">
                        <div class="related-price mr-auto">$120.00</div>
                        <div class="stars d-flex">
                            <div>&#9733;</div>
                            <div>&#9733;</div>
                            <div>&#9733;</div>
                            <div>&#9733;</div>
                            <div>&#9733;</div>
                        </div>
                    </div>
                </div>
            

        </div>
    </div>
</div>

script.js

let currentBooks = document.querySelector('.currentbooks')

async function bookTrends() {
    let currentdUrl = await fetch(`https://api.nytimes.com/svc/books/v3/lists/current/hardcover-fiction.json?api-key=apikey`)
    let currentBookData = await currentdUrl.json()
    let currntBookRes = currentBookData.results.books
    for(let i = 0; i < currntBookRes.length; i++){
        let currentBookItems = currntBookRes[i]
        let idCurrentBooks = currentBookItems.primary_isbn10
        let currentAuthor = currentBookItems.author
        let bookCurrent = currentBookItems.title
        let currentCoverImg = currentBookItems.book_image
        currentBooks.innerHTML += `<div class="col-lg-3 col-sm-6 d-flex flex-column align-items-center justify-content-center product-item my-3">
            <div class="product"> <img src="${currentCoverImg}" alt="">
                <ul class="d-flex align-items-center justify-content-center list-unstyled icons">
                    <li class="icon"><span class="fas fa-expand-arrows-alt"></span></li>
                    <li class="icon mx-3"><span class="far fa-heart"></span></li>
                    <li class="icon"><span class="fas fa-shopping-bag"></span></li>
                </ul>
            </div>
            <div class="tag bg-red">sale</div>
            <div class="title pt-4 pb-1" id="${idCurrentBooks}"><a href="details.html?id=${idCurrentBooks}">${bookCurrent}</a></div>
            <div class="d-flex align-content-center justify-content-center"> <span class="fas fa-star"></span> <span class="fas fa-star"></span> <span class="fas fa-star"></span> <span class="fas fa-star"></span> <span class="fas fa-star"></span> </div>
            <div class="price">${currentAuthor}</div>
        </div>`
    }
}
bookTrends()

details.js

let description = document.querySelector('.description')
let briefDesc = document.querySelector('.brief-description')
let productImg = document.querySelector('.product-image')
let bookDetTitle = document.querySelector('.title')

let urlParam = new URLSearchParams(window.location.search)
let bookId = urlParam.get('id')
let bookUrlId = `details.html?id=` + bookId

async function detailsBook(){
    let detailUrl = await fetch(`https://api.nytimes.com/svc/books/v3/lists/current/hardcover-fiction.json?api-key=apikey&id=${bookId}`)
    let rawDet = await detailUrl.json()
    let allDetsBooks = rawDet.results.books
    for(let i = 0; i < allDetsBooks.length; i++){
      let detItem =  allDetsBooks[i] 
      let bookDesc = detItem.description
      let bookDetImg = detItem.book_image
      let titleDet =  detItem.title
      console.log(titleDet)
      bookDetTitle.innerHTML = `<div class="title">${titleDet}</div>`
      description.innerHTML = `<p>${bookDesc}</p>`
      briefDesc.innerHTML = `<p>${bookDesc}</p>`
      productImg.innerHTML = `<img class="img-fluid" src="${bookDetImg}" alt="${titleDet}">`      
    }
}
detailsBook()

I want to show each id details in a details.html page if I click on any book. Currently, it’s showing one id details even if I click on any book.

How can add version suffix to end of some content of final build contents at Vite?

I am using Vite for building my REACT application. I am looking for adding a version query string at the end of some strings of final content of index.html and some image urls .

for example:
my index.html before building process is defined as :

  <link rel="shortcut icon" type="image/ico" href="/favicon.ico" />
  <link rel="manifest" href="./manifest.webmanifest">
  <script id="pwa:register-sw" src="./registerSW.js"></script>

Or in css files , the image url is defined as :

.class{
 background-image:url("/path/image.png");
}

An I’d like to add a suffix as version (at the end of all js and css sources and urls of images at css files).
The final index.html must be as :


  <link rel="shortcut icon" type="image/ico" href="./favicon.ico?v=version" />
  <link rel="manifest" href="./manifest.webmanifest?v=version">
  <script id="pwa:register-sw" src="./registerSW.js?v=version"></script>
  <script type="module" crossorigin src="./assets/index-Dhfu8acq.js?v=version"></script>
  <link rel="stylesheet" crossorigin href="./assets/index-C8LmPlD2.css?v=version">

and all image urls at css files be like :


.class{
  background-image:url("/path/image.png?v=version");
}

How can i do it ?

How to convert UTF8 to EUC-JP on the browser in JavaScript?

I need to convert UTF8 to EUC-JP which is the keyword in the URL in HTTP request.

Like ‘那賀崎ゆきね’ to %c6%e1%b2%ec%ba%ea%a4%e6%a4%ad%a4%cd

I find that TextDecoder can’t convert to EUC-JP, but the result is still UTF8.

This just converts EUC-JP to UTF8

const decoder = new TextDecoder('euc-jp');
const decodedString = decoder.decode(eucjpBytes); 

console.log(decodedString);

Or Encoding.js, encoding-japanese or iconv-lite from Node.js, needs the local environment.

But it seems there is no package to be required to achieve this on the browser.

Converting Node.js (npm) package to C++ for use in Go and C#

I have a npm package, which is basically a console application, that I need to use in both Go and C# applications. Direct conversion to C++ seems complex and time-consuming. What are the best approaches or alternatives to make this Node.js package accessible in Go and C# environments?
Key details:
The Node.js package is extensive, making manual conversion impractical

  • Need to use the package functionality in both Go and C# applications
  • Looking for efficient solutions that minimize code duplication
  • Open to alternatives like creating wrappers or using intermediary technologies

Has anyone successfully tackled a similar challenge? Any insights on best practices or potential pitfalls would be greatly appreciated.

Tried googling if someone’s ever done such a thing but it’s usually the other way around.

How do you build a React component that can be dynamically resized via both the left and right side, with the other side staying in place?

I’m trying to build a resizable component that can be resized from either the left or right side. The user should be able to change the width of the component from either the left or right side. If the user resizes from the left side of the component, the right side of the component should stay in place. If the user resizes from the right side of the component, the left side of the component should stay in place. The user also needs to be able to see this resize happening in real-time as they drag the end of the component back and forth.

I’ve got this (mostly) working – resizing from the right side works fine, but when resizing from the left side, the right side wiggles back and forth slightly. I assume this is because lots of updates are happening very quickly to the same piece of state, but I’m not sure how to fix it. I tried using a ref to track the size values and just update the size state on resize stop, which worked, but then the component was only re-rendered after the resize was completed, meaning the user couldn’t see the resize happening in real-time, which is a requirement here.

I’ve tried two different libraries for resizing components, react-resizable and re-resizable, and both produce the same issue.

Here’s a gif of what’s happening:

Resizable component glitching

And here’s a CodeSandbox with the minimum code I could put to reproduce the issue. Here’s the code if you don’t want to hop:

import React, { useState } from "react";
import { Resizable } from "re-resizable";
import "./styles.css";

export default function App() {
  const [size, setSize] = useState({ left: 100, width: 400 });

  const [dragStartSize, setDragStartSize] = useState(null);

  const onResize = function ({ delta, direction, size }) {
    setSize((prevSize) => {
      if (!dragStartSize) {
        return;
      }

      let newLeft = size.left;

      if (direction === "left") {
        newLeft = dragStartSize.left - delta.width;
      }

      let newWidth = dragStartSize.width + delta.width;

      return { ...prevSize, left: newLeft, width: newWidth };
    });
  };

  return (
    <div style={{ backgroundColor: "green" }}>
      <Resizable
        style={{
          position: "relative",
          left: `${size.left}px`,
        }}
        enable={{
          top: false,
          right: true,
          bottom: false,
          left: true,
        }}
        size={size}
        onResizeStart={() => {
          setDragStartSize(size);
        }}
        onResize={(event, direction, elementRef, delta) =>
          onResize({ delta, direction, size })
        }
        onResizeStop={(e, direction, ref, d) => {
          setDragStartSize(null);
        }}
      >
        <div
          style={{
            backgroundColor: "orange",
            padding: "5px",
            border: "2px solid black",
          }}
        >
          Resizable box
        </div>
      </Resizable>
    </div>
  );
}

Notice that when you quickly resize the resizable box from the right side, the left side stays nicely in place. But when you quickly resize it from the left side, the right side wiggles back and forth.

How can I make this work such that the right side doesn’t wiggle back and forth? Or is there maybe a library that does this for you already? I just can’t figure it out.

Does the term ‘initializer’ also refer to the initialization assignment?

I was learning about the new class syntax that allows you to put the field initialization code directly in the class body. The wording of the text I’m confused by is as follows:

The advantage of initializing your instance fields in this way is that this syntax allows (but does not require) you to put the initializers up at the top of the class definition, making it clear to readers exactly what fields will hold the state of each instance.

I know this is essentially saying ‘initializing your instance fields this way makes your code more readable,’ however, I don’t see how putting the field initializers themselves at the top of the class definition does this. I’d expect putting the FIELD INITIALIZATION CODE (the initialization assignments), instead of the field initializers, at the top of the class definition to do this; i’m confused as to whether the text was referring to the field initializers themselves or the field initialization code.

I’ve searched many different sources including Chatgpt, but it keeps changing what it believes ‘initializers’ refers to: sometimes it says it refers to the field initialization code and some other times, it says it refers to the initializers themselves.

Regex for lower case text space and dot or comma

Good day,

I am working on a project proofing, I have to identify spece between text and comma or dot, example coverage , I am using pdf to do the proofing, do we have any Java script which can highlight those text. Since it’s ebooklet with 600+ page it is time consuming for me to go each page.

I would like to remove the space after the text and dot or comma.

Free JavaScript Library for Extracting SCORM Zip Files

I’m currently working on an LMS platform that uses SCORM content. I need a JavaScript library that can extract and work with SCORM zip files. I’ve looked into @rusticisoftware/scormcloud-api-v2-client-javascript, but the paid version is quite expensive for our needs.

Does anyone know of any free or open-source alternatives for extracting and working with SCORM zip files in JavaScript? It would be ideal if the library supports SCORM 1.2 and SCORM 2004 formats.

Any help or recommendations would be greatly appreciated!

I’ve tried several other random libraries on GitHub, but I think they’re no longer working and maintained.

Slowly Make DIV come into screen then dim background

I have a div that pops up when I click an tag. This is achieved using JS.

    display: none;
    background-color: #100E0B;
    position: absolute;
    text-align: center;
    font-family: Georgia, 'Times New Roman', Times, serif;
    font-weight: bolder;
    width: 15vw;
    left: 45%;
    top: 40%;
    color: white;
    height: 20vh;
    border-color: #0B0A08;
    border-width: .125vw;
    border-style: solid;
    word-wrap: break-word;
    padding: 1.3vh;
    align-items: center; 
    justify-content: center; 
    flex-direction: column;
    transition: opacity 1s ease-in-out;


}

This is the CSS for the div that comes up after the is clicked.

function makeContactVisible() {
    var show = document.getElementById('showContact');
    
    show.style.display = "flex";
}

Here is the div:

        <div id = "showContact">
         <p id = "phoneNumber">+1 7</p>
         <p id = "email">@gmail.com</p>

        </div>

I have tried using: transition: opacity 1s ease-in-out;, but it has no effect, the div still instantly comes up.
I would also like to dim the background and “focus” the contact div when it is up.

Using the key attribute to control component refresh in vue failed

I need to click a button to modify the key value of the component through the bound function, and I find that the key value has changed, but the component is not unloaded for re-rendering.

I checked a lot of information on the Internet, found that they are so to achieve page refresh, this problem has been troubled for a long time.

I hope there are kind people to guide me how to correctly use the key attribute to complete the page refresh.

enter image description here

<template>
  <!-- 路由组件出口 -->
  <!-- v-slot可以获取当前渲染的组件以及路由信息 -->
  <router-view v-slot="{ Component }">
    <transition name="fade">
      <!-- 渲染home一级路由的子路由 -->
      <component :is="Component" :key="refreshContent"/>
    </transition>
  </router-view>
</template>

<script setup lang="ts">
import emitter from "@/utils/emitter";
import { onUnmounted, onMounted } from "vue";


let refreshContent = 0

emitter.on('refresh_content', () => {
  refreshContent += 1
  console.log(refreshContent)
})

onMounted(() => {
  console.log('load')
})

onUnmounted(() => {
  emitter.off('refresh_content')
  console.log('unload')
})

</script>

<style scoped>
.fade-enter-from {
  opacity: 0;
  transform: scale(0)
}

.fade-enter-to {
  opacity: 1;
  transform: scale(1);
}

.fade-enter-active {
  transform: all 0.5s;
}
</style>```

I need to click a button to modify the key value of the component through the bound function, and I find that the key value has changed, but the component is not unloaded for re-rendering.

I checked a lot of information on the Internet, found that they are so to achieve page refresh, this problem has been troubled for a long time.

I hope there are kind people to guide me how to correctly use the key attribute to complete the page refresh.

Codility max profit problem: why accumulated difference sum solution equivalent to 2 index difference solution?

An array A consisting of N integers is given. It contains daily prices of a stock share for a period of N consecutive days. If a single share was bought on day P and sold on day Q, where 0 ≤ P ≤ Q < N, then the profit of such transaction is equal to A[Q] − A[P], provided that A[Q] ≥ A[P]. Otherwise, the transaction brings loss of A[P] − A[Q].

For example, consider the following array A consisting of six elements such that:

  A[0] = 23171
  A[1] = 21011
  A[2] = 21123
  A[3] = 21366
  A[4] = 21013
  A[5] = 21367
If a share was bought on day 0 and sold on day 2, a loss of 2048 would occur because A[2] − A[0] = 21123 − 23171 = −2048. If a share was bought on day 4 and sold on day 5, a profit of 354 would occur because A[5] − A[4] = 21367 − 21013 = 354. Maximum possible profit was 356. It would occur if a share was bought on day 1 and sold on day 5.

Write a function,

class Solution { public int solution(int[] A); }

that, given an array A consisting of N integers containing daily prices of a stock share for a period of N consecutive days, returns the maximum possible profit from one transaction during this period. The function should return 0 if it was impossible to gain any profit.

For example, given array A consisting of six elements such that:

  A[0] = 23171
  A[1] = 21011
  A[2] = 21123
  A[3] = 21366
  A[4] = 21013
  A[5] = 21367
the function should return 356, as explained above.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [0..400,000];
each element of array A is an integer within the range [0..200,000].

https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_profit/

Here is a solution where I found on youtube

function solution(arr) {
    let max = 0;
    let acc = 0;

    for(let i=1; i<arr.length; ++i) {
        const diff = arr[i] - arr[i-1];
        acc = acc + diff;
        if(acc > 0) {
            if(acc > max) {
                max = acc;
            }
        } else {
            acc = 0;
        }
    }

    return max;
}

my question is below:

In this test case above, we know that array[five] – array[one] = 356 (we buy at day 5 and sell at day 1 to get max profit), in one transaction. We do not consider anything in between and that is what the question is asking

Using the accumulated difference sum and add them up together (hence other numbers come in and interference the calculation)

Why accumulated difference sum is equivalent to array[five] – array[one] = 356?

enter image description here

Invalid $addFields :: caused by :: undefined variable: setNumberPart

I’ve been developing an app to track my trading card collection. I’m attempting to use an aggregate pipeline for sorting cards at the database level since this app will contain a ton of data. I’m very new to aggregates, and I keep running into the issue where my setNumberPart variable is out of scope when referenced and I can’t seem to figure out a way to be within scope. Here is my pipeline code:

        const pipeline = [
          { $match: query }, // Match documents based on the query

          {
            $addFields: {
              numericSetNumber: {
                $let: {
                  vars: {
                    // Extract the relevant part of setNumber based on prefix
                    setNumberPart: {
                      $cond: [
                        { $regexMatch: { input: "$setNumber", regex: /^GG/ } },
                        { $arrayElemAt: [{ $split: ["$setNumber", "/"] }, 0] },
                        {
                          $cond: [
                            {
                              $regexMatch: {
                                input: "$setNumber",
                                regex: /^TG/,
                              },
                            },
                            {
                              $arrayElemAt: [
                                { $split: ["$setNumber", "/"] },
                                0,
                              ],
                            },
                            {
                              $cond: [
                                {
                                  $regexMatch: {
                                    input: "$setNumber",
                                    regex: /^SWSH/,
                                  },
                                },
                                {
                                  $arrayElemAt: [
                                    { $split: ["$setNumber", " "] },
                                    -1,
                                  ],
                                },
                                "$setNumber", // Default case if no prefix matches
                              ],
                            },
                          ],
                        },
                      ],
                    },
                    // Remove non-numeric characters from setNumberPart
                    cleanedSetNumber: {
                      $replaceAll: {
                        input: "$$setNumberPart",
                        find: "[^0-9]", // Pattern to keep only numeric characters
                        replacement: "",
                      },
                    },
                  },
                  in: {
                    // Convert cleaned number to integer or default to 0 if empty
                    $cond: [
                      {
                        $regexMatch: {
                          input: "$$cleanedSetNumber",
                          regex: /^d+$/, // Ensure it's numeric
                        },
                      },
                      { $toInt: { $ifNull: ["$$cleanedSetNumber", "0"] } },
                      0,
                    ],
                  },
                },
              },
            },
          },

          ...(Object.keys(sortStage).length > 0 ? [{ $sort: sortStage }] : []),
          { $skip: offset },
          { $limit: limit },
        ];

Any help getting this variable to stop being undefined is much appreciated!

I tried adding another $let inside the cleanedSetNumber variable and defined $$setNumberPart there, but it still showed as undefined.