how to append element dynamically to other element in react?

function RenderFolders({data}){
    if(!data) return
    const res=[]
    res[0]= React.createElement('div', {className:'total-wrap folder-wrap', id:0})
    const arr=[data]
    
    while(arr.length!==0){
      const now=arr.pop()

      for(let key in now.children){
        arr.push(now.children[key])
        if(now.children[key].type==='folder'){
          res[now.children[key].id]= 
            <div className='folder' id={now.children[key].id}>
              <div>{key}</div>
              <div className='folder-wrap'></div>
            </div>
          res[now.id].appendChild(res[now.children[key].id])
        } else{
          res[now.children[key].id]= 
            <div className='file' id={now.children[key].id}>
              <div>{key}</div>
            </div>
          res[now.id].appendChild(res[now.children[key].id])
        }
      }
    }
    return res
  }

i fetched folder/file data and wanted to transform it to html element.
The folder/file data is object type, which is sent as parameter.
I tried to use dfs algorithm to referring folder/file structure, because I don’t know how many folders/files is in a folder and what folders/files is in a folder.
But I couldn’t find a way.

Is there a way to make react element and dynamically append it to other element in dfs algorithm?

Is the await keyword blocking

I’m currently reading ‘Javascript: The Definitive Guide’ and I have a question in relation to the asynchrony of the await keyword.
In the book it states ‘think of the await keyword as a marker that breaks up a function body into seperate synchronous chunks‘. I presumed the only purpose of this would be to run each of them concurrently.

But in relation to the below example, the book states that ‘fetching of the 2nd URL will not begin until the first fetch is complete‘. And so I’m a bit confused as both statements seem contradictory. Any help would be appreciated. Thanks

let value1 = await getJSON(url1);
let value2 = await getJSON(url2);

How can I use setAttribute() with class name

I have the following htmlhelper line:

@Html.ActionLink("Details", "LeadDetails", new {@class = "detailsLink", id = item.user_id, urlfrom = "ManageDeposits" })

on urlform I want to pass the current url using javascript.

I do not know what the specific ActionLink’s id is so I decided to use class name detailsLink

However when I use: const det = document.getElementByName("detailsLink");
I cannot use the setAttribute() function.

Are there any alternatives to use setAttribute() by getting the element using class name instead of id?

What is the difference between declaring variables in data or setup function?

I am new to Vue and as I see it, both functions can be used to define/initialize variables used in the file. But from what I read it is not clear to me what the differences are and when I should use which one to declare/initialize variables.

So far I’ve only realized that variables declared in the data function are then wrapped in a proxy object, which causes troubles when I try to save the object in a database. Now I’m thinking whether I should keep using the data function and create a normal object from the proxy when I need to save it, or whether I should instead just use the setup function.

In case it’s not clear what I’m talking about:

Example A:

data() {
  return {
    person: {
      age: 5,
      name: "Peter"
    }
  }
}

Example B:

setup() {
  return {
    person: {
      age: 5,
      name: "Peter"
    }
  }
}

How to exclude one key/value pair from spread operator return

Let say I have an object and a function that takes one update object and return a new object with the first one and the update one like so :

const object = {
    id: 1,
    value: 'initial value'
}

const updateFunction = (updates) => {
    return {
        ...object,
        ...updates
    }
}

const updatedObject = updateFunction({
    id: 2,
    value: 'updated value'
})

Using the spread operator is there a simple way to exclude the id from spreading thus updating it knowing that I absolutely can’t change my updateFunction to take multiple arguments

thank you

Vitest+Typescript: TypeError: Cannot set property X of # which has only a getter

need some advice on creating a TS class with private/protected readonly members.

asset.ts

  STOCK,
  CRYPTO,
}
export abstract class Asset {
  protected readonly _type: AssetType;
  protected readonly _symbol: string;
  protected readonly _name: string;
  protected _amount: number;
  protected readonly _initialPrice: number;

  constructor(
    type: AssetType,
    symbol: string,
    name: string,
    amount: number,
    initialPrice: number,
  ) {
    this._type = type;
    this._symbol = symbol;
    this._name = name;
    this._amount = amount;
    this._initialPrice = initialPrice;
  }

  get type(): AssetType {
    return this._type;
  }

  get symbol(): string {
    return this._symbol;
  }

  get name(): string {
    return this._name;
  }

  get amount(): number {
    return this._amount;
  }

  set amount(amount: number) {
    this._amount = amount;
  }

  get initialPrice(): number {
    return this._initialPrice;
  }
}

stock.ts:

import { Asset, AssetType } from '@core/asset';

export class Stock extends Asset {
  constructor(
    symbol: string,
    name: string,
    amount: number,
    initialPrice: number,
  ) {
    super(AssetType.STOCK, symbol, name, amount, initialPrice);
  }
}

broker.test.ts

import { describe, it, expect, beforeAll } from 'vitest';
import { Broker } from '@core/broker';
import { Position } from '@core/position';
import { Stock } from '@core/stock';

let stock: Stock;

beforeAll(() => {
  stock = new Stock('XYZ', 'XYZ Co.', 1000, 1.0);
});

describe('addPosition', () => {
  it("should add position to the broker's positions", () => {
    const positions: Position[] = [];
    const broker: Broker = new Broker('John Smith', positions);
    const newPosition: Position = new Position(stock, 1);

    expect(broker.positions).toEqual([newPosition]);
  });
});

Result after running vitest:

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Failed Suites 1 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯

 FAIL  src/core/broker/broker.test.ts > addPosition
TypeError: Cannot set property asset of #<Position> which has only a getter
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/2]⎯

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯

 FAIL  src/core/broker/broker.test.ts > addPosition > should add position to the broker's positions

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Unhandled Error ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
TypeError: Cannot read properties of undefined (reading 'stacks')
 ❯ parseStacktrace file:/home/ffknob/Entwicklung/workspace/ffknob/x-udemy-js-unit-testing/node_modules/vitest/dist/chunk-utils-timers.8a5e7cd5.js:5678:9
 ❯ printError file:/home/ffknob/Entwicklung/workspace/ffknob/x-udemy-js-unit-testing/node_modules/vitest/dist/chunk-vite-node-externalize.92c54acc.js:10045:18
 ❯ Vitest.printError file:/home/ffknob/Entwicklung/workspace/ffknob/x-udemy-js-unit-testing/node_modules/vitest/dist/chunk-vite-node-externalize.92c54acc.js:10623:12
 ❯ VerboseReporter.printTaskErrors file:/home/ffknob/Entwicklung/workspace/ffknob/x-udemy-js-unit-testing/node_modules/vitest/dist/chunk-vite-node-externalize.92c54acc.js:8640:22
 ❯ VerboseReporter.reportSummary file:/home/ffknob/Entwicklung/workspace/ffknob/x-udemy-js-unit-testing/node_modules/vitest/dist/chunk-vite-node-externalize.92c54acc.js:8591:18
 ❯ processTicksAndRejections node:internal/process/task_queues:96:5
 ❯ async VerboseReporter.onFinished file:/home/ffknob/Entwicklung/workspace/ffknob/x-udemy-js-unit-testing/node_modules/vitest/dist/chunk-vite-node-externalize.92c54acc.js:8486:5
 ❯ async VerboseReporter.onFinished file:/home/ffknob/Entwicklung/workspace/ffknob/x-udemy-js-unit-testing/node_modules/vitest/dist/chunk-vite-node-externalize.92c54acc.js:9266:5
 ❯ async Vitest.report file:/home/ffknob/Entwicklung/workspace/ffknob/x-udemy-js-unit-testing/node_modules/vitest/dist/chunk-vite-node-externalize.92c54acc.js:10574:5


So, since I’m not the one setting the property explicit with a setter, I guess that’s something vitest is doing somehow…

Any thoughts?

Thank you

Writable Stream empties the file but do not write expected content in nodeJS

This is my code to get an array of records and rwite them as CSV string one by one in a file. I cannot get the writable stream to write in the file. It just erases whatever is in the file and does not write the new data in.

const writeStream = fs.createWriteStream(process.env.SAVED_FILE);
const transformStream = new Stream.Transform({
    writableObjectMode: true,
    readableObjectMode: true,
})
transformStream._transform = (chunk, encoding, callback) => {
    console.log(chunk);
    transformStream.push(""" + chunk.join("","") + """);
    callback();
}
const readable = new Stream.Readable({objectMode: true})
    .pipe(transformStream)
    .pipe(writeStream);
let records = [["a", "b"], [1, 2], ["c", "d"], [8, 9]];
records.forEach(record => readable.push(record));
readable.push(null);

writeStream.on("error", function (err) {
    res.send(err.stack);
});
writeStream.on("end", function () {
    res.send("Data Saved");
});

Any help appreciated on this basic example !

How to avoid circular dependencies in Javascript / Typescript?

What is the best practice to avoid circular dependencies? I had this problem with Javascript but it also applies to any other programming language.

For example I have this translationService.ts module where whenever a locale is changed, I want to reload settings (so I need to import the settingsService.ts. But in my settingsService.ts I have a function reloadSettings which uses the translationService to translate the error message.

I guess you could say that the translationService should not know anything about the settingsService but how do you actually write the code to accomplish that?

translationService.ts

import { reloadSettings } from '@/services/settingsService.ts'

// When the locale is changed, we want to reload the settings
const changeLocale = (locale: string) => {
  i18n.locale = locale

  reloadSettings()
}

But in my settingsService.ts I have a dependency on the translationService in order to show the exception in the correct locale.

settingsService.ts

import settingsApi from '@/api/settingsApi.ts'
import { translate } from '@/services/translationService.ts'

const reloadSettings = () => {
  try {
    settingsStore.settings = settingsApi.getSettings()
  } catch (error) {
    console.log(
      translate(error.message)
    )
  }
}

So I end up with circular dependencies where settingsService depends on translationService and translationService depends on settingsService

settingsService -> translationService -> settingsService

Fix CORS violation on MS edge (not cross domain) Request had a target IP address space of `unknown`

Access to XMLHttpRequest at ‘https://www.MYWEBSITE.com.au//COMPANY-supplier/include/includes/common/auto-people.php?term=a&clid=12345678’ from origin ‘https://www.MYWEBSITE.com.au’ has been blocked by CORS policy: Request had a target IP address space of unknown yet the resource is in address space public.

I am getting this error when doing a simple POST request using jquery (3.6.0). I’m unsure how to solve this. There are no other domains involved. The upload payload has a dataUrl collected from a file input tag and some ids. Other jquery AJAX requests seem ok. This problem is intermittent (1 in 10 time) and doesn’t happen every time. If someone (smarter than me) can suggest how to include a header that changes the address space to ‘public’, this may solve the problem.

Nextjs CSR load the code for multiple pages for one page req

Using Client Side Navigation I can navigate between pages using only javascript. The first request of a page takes some time to render and then the navigation back to it is nearly instant. During that first render that page only loads what’s necessary for it. That isolates each page making them independent. I just want to know, if there was a way to load the code for more than one page on a single request. As an example, let’s say I have multiple profile pages for a user (info, settings, history). I want to load the code for all of those pages on one request for any of those pages, so the navigation between them will be instant, and there will be no waiting time.

Build a drivers leaderboard using a defined criteria

I wish to build a drivers leaderboard based on the individuals performance.

driver  = [];
    
    for(n=0; n<=4; n++){
        driver[n]       = new Object();
        driver[n].rank  = n;
        driver[n].name  = "Driver "+n;
        driver[n].pts   = 10;
        driver[n].placings  = new Array();
        for(a=0; a<=4; a++){
            driver[n].placings[n][a]    = 0;
        }
    }
    
    driver[0].placings[0]   = 2;    //  [0] == 1st place;
    driver[0].placings[1]   = 1;    //  [1] == 2nd place;
    driver[0].placings[2]   = 0     //  [2] == 3rd place;
    driver[0].placings[3]   = 1;    //  [3] == 4th place;
    driver[0].placings[4]   = 0;    //  [4] == 5ht place;
    
    driver[1].placings[0]   = 2;
    driver[1].placings[1]   = 0;
    driver[1].placings[2]   = 0
    driver[1].placings[3]   = 1;
    driver[1].placings[4]   = 1;
    
    driver[2].placings[0]   = 1;
    driver[2].placings[1]   = 0;
    driver[2].placings[2]   = 0
    driver[2].placings[3]   = 0;
    driver[2].placings[4]   = 3;
    
    driver[3].placings[0]   = 0;
    driver[3].placings[1]   = 0;
    driver[3].placings[2]   = 3
    driver[3].placings[3]   = 0;
    driver[3].placings[4]   = 1;

    driver[4].placings[0]   = 2;
    driver[4].placings[1]   = 1;
    driver[4].placings[2]   = 0
    driver[4].placings[3]   = 1;
    driver[4].placings[4]   = 0;
    
    // Drivers are ranked according to the number of pts scored - in this example over the season each driver has scored 10pts (driver[n].pts). 
    // If drivers are tied for a position, a countback system is used, with the driver registering the most gp race wins ranked highest (driver[n].placings);
    // If they are tied on race wins, seconds, then third, fourth and fifth places are taken into consideration. 
    // If this cannot split them the lowest rank takes precedence (driver[n].rank);

The criteria for the result should be as follows: Drivers are ranked according to the number of pts scored – in this example over the season each driver has scored 10pts (driver[n].pts).

If drivers are tied for a position, a countback system is used, with the driver registering the most gp race wins ranked highest (driver[n].placings);

If they are tied on race wins, seconds, then third, fourth and fifth places are taken into consideration.

If this cannot split them the lowest rank takes precedence (driver[n].rank) – (in this case both driver[0] and driver[4] have identical records – driver[0] would take precedence as he is ranked higher).

If it was purely on points I know how to work this out but adding the additional criteria has foxed me – I initially had the idea of multiplying by 10, 100, 1000, 10000, 100000 on each placing and then sort that number.

How to transform a glob string to a JavaScript regex? [closed]

I’ve a command from CLI that runs a Node script to operate across my repository, searching packages through the name property of all package.jsons.

I want to allow the user to use super easy regex just with the use of asterisk, so for instance a command like the following

yarn my-command "@namespace/component-list*"

should find packages with name

{
  ...
  name: "@namespace/component-list"
  ...
}

{
  ...
  name: "@namespace/component-list-square"
  ...
}


{
  ...
  name: "@namespace/component-list-triangle"
  ...
}

with the following JavaScript code:

const packageNameRegEx = new RegExp(commandArgument)
packageNameRegEx.test(packageName)

But what I notice is this issue, that regex built with JavaScript class new RegExp(commandArgument) is not working for all cases:

command: yarn my-command "@namespace/component-list-*" expected received
const packageNameRegEx1 = new RegExp('@namespace/component-list-*')
console.log(packageNameRegEx1.test("@namespace/component-list-square")) true true
console.log(packageNameRegEx1.test("@namespace/component-list-triangle")) true true
console.log(packageNameRegEx1.test("@namespace/component-list")) true true
command: yarn my-command "@namespace/component-*list" expected received
const packageNameRegEx2 = new RegExp('@namespace/component-*list')
console.log(packageNameRegEx2.test("@namespace/component-square-list")) true false
console.log(packageNameRegEx2.test("@namespace/component-triangle-list")) true false
console.log(packageNameRegEx2.test("@namespace/component-list")) true true

What is the best approach to create a JavaScript regex? Shall I transform the * into a [a-zA-Z-0-9]*?