SvelteMap not reactive

I’m trying to use SvelteMap: https://svelte.dev/docs/svelte/svelte-reactivity#SvelteMap

but for some reason it’s not reactive.

I am exporting it from a .svelte file:

export const items = new SvelteMap<number, Item>();

Item is an object.

Then inside a function I change the contents, like:

const item = items.get(num);
item.someProp = newValue;

The map is update, but reactivity doesn’t work in components.

I also tried to re-assign the item in that function

const item = items.get(num);
item.someProp = newValue;
items.set(num, item);

still no go..

Reduce JavaScript character count for longest common substring finder (currently 167 chars)

I’m trying to further reduce the character count of this JavaScript code snippet. The code finds the longest common substring among command-line arguments.

Current Code (167 characters):

x = process.argv.slice(2), y = x[0]||'', z = '', l = y.length;

for (d=0; d<l; d++)
    for (e=d+1; e<=l; e++)
        f = y.slice(d, e),
        f.length > z.length
           && x.every(h => h.includes(f))
           && (z=f);
console.log(z)

Functionality:

The code takes command-line arguments as input. It treats the first argument as the primary string to generate substrings from. It then iterates through all substrings of the first argument and checks if each substring is present in every command-line argument. It outputs the longest substring that is common to all arguments.

Example:

Photo

Count actual replacements

Overview

I’ve created a basic text editor with a “Replace all” feature. However, I’m facing an issue where the output indicates replacements were made even when the text remains unchanged. Here’s a simplified version of my code:

const textarea = document.getElementById('textarea');
const searchInput = document.getElementById('search');
const replaceInput = document.getElementById('replace');
const output = document.getElementById('output');
const replaceButton = document.getElementById('replaceAll');

replaceButton.addEventListener('click', () => {
  const searchValue = searchInput.value;
  const replaceValue = replaceInput.value;

  if (!searchValue) {
    output.textContent = 'No search term';
    return;
  }

  const regex = new RegExp(searchValue, 'g');
  const matches = textarea.value.match(regex);

  if (matches) {
    const count = matches.length;
    textarea.value = textarea.value.replace(regex, replaceValue);
    output.textContent = `${count} replacement${count === 1 ? '' : 's'}`;
  } else {
    output.textContent = 'No matches';
  }
});
textarea {
  width: 100%;
  height: 100px;
}

#output {
  color: #666;
}
<textarea id="textarea">apple orange apple orange</textarea>
<input type="text" id="search" placeholder="Search">
<input type="text" id="replace" placeholder="Replace">
<button id="replaceAll">Replace all</button>
<div id="output"></div>

Edge cases

Non-regex search

  • Text: apple orange apple orange
  • Search: apple
  • Replacement: apple
  • Expected output: “No replacement”
  • Current output: “2 replacements”

Regex search

  • Text: 9/1/2021, 3/1/2022
  • Search: (d*)/d*/(d{4})
  • Replacement: $1/1/$2
  • Expected output: “No replacement”
  • Current output: “2 replacements”

Question

How can I modify the code to correctly handle these edge cases and display “No replacement” when the text remains unchanged after the replacement operation?

Why are my global declarations in index.d.ts not being recognized in my TypeScript project?

I’m working with a TypeScript project where I have two files:

  • index.ts – This file contains the main application logic.
  • index.d.ts – This file is where I declare global types.

In my index.d.ts, I’m declaring globals like this:

declare global {
  namespace Express {
    interface Request {
      user_id?: number;
      role?: string;
    }
  }
}

export {};

However, it seems that the global declarations are not being recognized in my project. If I rename index.d.ts to any other name (e.g., globals.d.ts), the global declarations work perfectly fine.

My Questions:

  1. Why are the global declarations in index.d.ts not being recognized?
  2. Does the file name index.d.ts affect the recognition of global types in TypeScript?
  3. How can I fix this issue so that my global types in index.d.ts are properly recognized?

I’ve ensured that index.d.ts is included in the tsconfig.json file under the include array, but the issue persists.

Things I’ve already tried:

  • Renamed the file to other names (e.g., globals.d.ts) and it works fine.

Any help would be appreciated!


This should help others understand your issue and offer suggestions for resolving it!

Why can’t I import @yaml-js/vite?

Following this documentation: https://www.npmjs.com/package/@yaml-js/vite

I installed yaml-js with this command:

yarn add -D @yaml-js/vite

Then changed my vite.config.ts to this:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import yaml from '@yaml-js/vite'

export default defineConfig({
  plugins: [react(), yaml()],
})

The I added this line to one of my files:

import { foo } from "../data/foo.yaml"

I got this error log. I’ve removed the stack traces for brevity. They are all traces within yaml-js not my code, obviously. My relevant code is just the above import line where the error starts.

yarn run dev
yarn run v1.22.22
$ vite
✘ [ERROR] Failed to resolve entry for package "@yaml-js/vite". The package may have incorrect main/module/exports specified in its package.json. [plugin externalize-deps]

    node_modules/esbuild/lib/main.js:1225:27:
      1225 │         let result = await callback({
           ╵                            ^

  This error came from the "onResolve" callback registered here:

    node_modules/esbuild/lib/main.js:1150:20:
      1150 │       let promise = setup({
           ╵                     ^

  The plugin "externalize-deps" was triggered by this import

    vite.config.ts:3:17:
      3 │ import yaml from '@yaml-js/vite'
        ╵                  ~~~~~~~~~~~~~~~

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error: Recipe `dev` failed on line 5 with exit code 1

Does React enforces the same number and order of hooks across all instances of a component?

Suppose I have two instances of the same component. One uses a custom hook with two useState calls, and another uses a different custom hook with three useState calls. Intuitively, since they’re separate instances, their state should be independent.

I came up with a sample implementation which works fine having different number of hooks for 2 different instances of the same component (MyComponent). This is achieved via conditionally plugging a custom hook to the component body when mounting with the help of a useState. Is there any drawbacks?

Note: The following logic can also be used to set custom hook conditionally

const conditionalHook = (count % 2 === 1) ? useCustomB : useCustomA;

But this is highly error prone as number and order of hooks can change even for a single component instance as prop values are modified

Please refer to the working sample implementation below

import { useEffect, useRef, useState } from 'react'

const useCustomA = (count) => {
  const [val, setVal] = useState('');

  useEffect(() => {
    console.log("A Effect called");
    setVal('State A' + count);
  }, [count]);
  
  return `${val}`;
};

const useCustomB = (count) => {
  const [val, setVal] = useState('');
  const [rnNum, setRnNum] = useState(0);

  useEffect(() => {
    console.log("B Effect called");
    setVal('State B' + count)
    setRnNum(Math.random())
  }, [count]);

  return `${val}-${rnNum}`;
};

const MyComponent = ({count}) => {

  //Please note that conditional hook won't change between re-renders for a single component instance
  //since it is determined using a useState init function, 
  //but can change for different instances on mounting
  const [conditionalHook] = useState(() => (count % 2 === 1) ? useCustomB : useCustomA);
  const value = conditionalHook(count)

  return (
    <>
      <div>Value: {value}</div>
    </>
  )
};


const App = () => {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
  }

  return (
    <div>
      <MyComponent count={count}/>
      <MyComponent count={count+ 1}/>
      <div>Count: {count}</div>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}

export default App

Please see the following React dev tools output for these 2 instances

enter image description here

enter image description here

Why is my React component not re-rendering when the state updates?

I’m working on a banking application that needs to maintain many previous values in the frontend. Even though I update the state, it does not trigger a re-render. Is this an expected behavior, or should I be maintaining this data separately to ensure proper updates?

Here is a sample code to demonstrate the issue:

const { useState } = React;

const Example = () => {
  const [count, setCount] = useState(0);
  const [prevCount, setPrevCount] = useState(0);

  console.log(count);

  const handleClick = () => {
    setPrevCount(count);
    setCount(count + 1);
  };

  return (
    <div>
      <h1>Count: {count}</h1>
      <h2>Previous Count: {prevCount}</h2>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
};

ReactDOM
  .createRoot(root)
  .render(<Example />);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>

<div id="root"></div>

I put a console log to track this issue but its only printed only once.

Globally enable HMR for Pinia without adding ‘if (import.meta.hot)’ in every store

I’m using Pinia in a Vue 3 + Quasar project, and I want to enable Hot Module Replacement globally, so I don’t have to add if (import.meta.hot) in every store file. Is it possible to do so, maybe somewhere in the src/stores/index.ts?

Right now, I have something like this in each store:

import { defineStore, acceptHMRUpdate } from 'pinia';

export const useStoreProducts = defineStore('products', {
  state: () => ({
    products: [],
  }),
  actions: {
    async loadProducts() {
      console.log('Loading products...');
    },
  },
});

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useStoreProducts, import.meta.hot));
}

I’m looking for a possible solution.

ERROR: The JSX syntax extension is not currently enabled (in angular project)

I am using angular and need to run a javascript code which contains html tags as well (I am not sure if it is now js file or jsx file!). Following is my code:

export function initialize(){
    startBtn = document.getElementById("start-btn");   
    startBtn.addEventListener("click", () => {
       alert("Started!")        
    });
}
<>
<button id="start-btn" class="btn">Start</button>
</>

and my runjavascript.component.ts:

import * as myGame from "../../../../assets/myGame.js"
.
.
.
export class RunJavascriptComponent {
    constructor() {
       myGame.initialize()
    }    
}

The error I get is:

The JSX syntax extension is not currently enabled
angular:script/global:scripts.js:4731:0:

I see this error has been reported and is also solved in react community, but not in angular.

Does any one know how to solve it in angular?

How to Virtualize Rows Inside an Expandable Panel in React Virtualized?

I am using React Virtualized to render a list with expandable panels. The issue is that when a panel expands, all 500+ rows inside it are loaded at once, making the UI very slow.

The outer list is virtualized, but I also want to virtualize the rows inside the expanded panel so only visible rows are rendered.

Wrapping the inner rows with List from react-virtualized, but it didn’t work as expected.
Facing issues with height calculations when trying to virtualize both levels.
How can I efficiently virtualize the inner rows inside an expanded panel?

Here’s my CodeSandbox link showing the issue:

Reference

Any suggestions would be appreciated!

Algolia Autocomplete Select List Event

I am trying to use algolia autocomplete, the list appears fine but when we click on it, no event fires, the keyword scroll is also working but the section on the list is not.

https://jsfiddle.net/qeLwbfpj/

const { autocomplete } = window['@algolia/autocomplete-js'];

var ac_instance = autocomplete({
    insights: true,
    container: '#autocomplete',
    placeholder: 'Type a name...',
    openOnFocus: true,

    getSources({ query }) {
        return [
            {
                sourceId: 'dummy-source',
                getItems() {
                    return [
                        { label: 'Apple', Id: '123' },
                        { label: 'Mango', Id: '456' },
                        { label: 'Banana', Id: '789' },
                        { label: 'Orange', Id: '101' }
                    ].filter(item => item.label.toLowerCase().includes(query.toLowerCase()));
                },
                templates: {
                    item({ item }) {
                        return item.label;
                    }
                }
            }
        ];
    },

    onSelect(item ) {
        console.log(`File: dummy.php, Line: 62`, item);
        alert(`File: dummy.php, Line: 63`);
    },

    onSubmit(state) {
        alert(`File: dummy.php, Line: 67`);

    }
});

console.log(`File: dummy.php, Line: 79`, ac_instance);

Any help is appreciated.

Thank you

Google-Forms EventListner

I am now struggling for a while with my hmtl code. The first console logs of my code appear, but the ones inside of the function onSubmit() dont appear, but i also know that the function is running, because google.script.run.processForm() is getting called and there is also no error message. I couldnt figure out a solution to the problem yet.

<!DOCTYPE html>
<html>
  <head>
    <script>
      console.log("Page loaded, preparing to submit form");

      window.onload = function() {
        var form = document.querySelector('form');
        console.log(form)
        form.addEventListener('submit', onSubmit); // Listen for the submit event
      }

      function onSubmit(event) {
        event.preventDefault();

        alert("onSubmit() was called!");
        console.log("Form submitted");

        google.script.run
          .withSuccessHandler(function (url) {
            console.log("Redirecting to:", url);

            if (typeof url === "string" && url.startsWith("https://")) {
              window.open(url, "_self");
            } else {
              alert("Error: Invalid PayPal link.");
            }
          })
          .processForm();
      }
    </script>
  </head>
  <body>
    <form>
      <iframe src="https://docs.google.com/forms/d/e/(private)/viewform?embedded=true" width="640" height="1169" frameborder="0" marginheight="0" marginwidth="0">Wird geladen…</iframe>
    </form>
  </body>
</html>

My original goal was that on submiting the form a paypal page would open, but nothing happend so i added the logs which didnt log anything.

I am really thankfull for any help 😀

Sorting javascript object in vue file

I have a object wit values (name)
So now i want to sort this array by value.
Here is what i got:

admin_table_id' => [
        '2' => 'blogs',
        '15' => 'users',
        '18' => 'users_rights',
        '19' => 'didyouknow',
        '30' => 'admin_table',
        '37' => 'privacy'
    ]

and i want something like:

'admin_table_id' => [
       '30' => 'admin_table',     
        '2' => 'blogs',
        '19' => 'didyouknow',
        '37' => 'privacy'
        '15' => 'users',
        '18' => 'users_rights',
   ]

i tried different sort functions but he doesn’t sort by value
I need this for a <select> field in a vue component

the code i tried is here:

        sortedOptions() {
    if (!this.options || !Array.isArray(this.options)) return [];



    const sorted = this.options.map(obj => {
        return Object.fromEntries(
            Object.entries(obj).map(([outerKey, innerObj]) => {
                const rawInnerObj = innerObj;


                const sortedInner = Object.fromEntries(
                    Object.entries(rawInnerObj)
                        .sort(([, a], [, b]) => {

                            if (typeof a === 'string' && typeof b === 'string') {
                                return a.localeCompare(b);  
                            } else if (typeof a === 'number' && typeof b === 'number') {
                                return a - b;
                            }
                            return 0;
                        })
                );

                return [outerKey, sortedInner];
            })
        );
    });

    nextTick(() => {
        console.log("Nach der Sortierung:", JSON.stringify(sorted, null, 2));
    });

    return sorted;
}