What is a factory function?

I understand that this question may be considered broad. I am currently learning Javascript and throughout the process I’ve stumbled upon different terms of functions that are thrown around such as: factory function, and constructor functions regarding to object-oriented programming. I am having trouble understanding these terms and finding the distinction among them, although based upon my personal understanding; factory functions are basically regular functions, or am I not seeing the bigger picture in all this? Anyways I hope my brief description of this concept can somehow help in some sort of way.

How to get ul inside an li

<li class="cate-item"> 
<button class="cate-label" >item 1 </button>
    <ul class="sub-categ">
    <li> sub item 1</li>
    <li> sub item 2</li>
    <li> sub item 3</li>
    <li> sub item 4</li>
    </ul>
</li>

<li class="cate-item"> 
<button class="cate-label" >item 2 </button>
<ul class="sub-categ">
    <li> sub item 1</li>
    <li> sub item 2</li>
    <li> sub item 3</li>
    <li> sub item 4</li>
    </ul>
</li>

This li item is generated dynamically I want to toggle li on the cate-label button click. for that, I did the following code

  $(document).on("click", "#categoryList > li .cate-label", function () {
      var currentItem = $(this).closest("li");
      ItemToHide = $("#categoryList > li").not(currentItem);
        ItemToHide.removeClass("active-item");
    ItemToHide.find(".sub-cate").hide();
      currentItem.toggleClass("active-item");
     
     
     }
     
     );

when I try to hide item using ItemToHide.find(“.sub-cate”).hide(); it didn’t hide anything . I tried to find the length of the item using ItemToHide.find(“.sub-cate”).length but it returned 0.

angular-file change event call function after browsing and opening the file

I am using angular-file npm file package to upload file (https://www.npmjs.com/package/angular-file) . I want to know how do we directly call the method after we browse files ?

When I browse files and click open it will automatically check the progress and will upload the file without clicking any submit or any buttons any other buttons , it will upload after browsing the files.

How do we call the uploadFile after click the browse file and opening the file? I tried adding (change)=”handleFileInput($event.target.files)” but it does not seem to work. Any idea guys ? Thank you.

enter image description here

enter image description here

#html code

<div ngfDrop class="well my-drop-zone drop-box" selectable="selectable"
                        [(validDrag)]="baseDropValid" (fileOver)="hasBaseDropZoneOver=$event" [(files)]="files"
                        [accept]="accept" [maxSize]="maxSize" [(dragFiles)]="dragFiles" [(lastInvalids)]="lastInvalids"
                        class="well my-drop-zone drop-box" [class.invalid-drag]="baseDropValid===false"
                        [class.valid-drag]="baseDropValid" [fileDropDisabled]="fileDropDisabled"
                        [class.invalid-drag]="baseDropValid===false" [class.valid-drag]="baseDropValid"
                        [ngfFixOrientation]="false">
                        <div id="file-drop-area">
                            <span class="material-icons material-icons-outlined tertiary-text"
                                style="font-size: 36px;margin-bottom:33px;">
                                cloud_upload
                            </span>
                            <div class="mb-8px">
                                <span style="font-size:14px;">Drag and drop files here or </span>
                                <span (click)="ok()"class="primary-color cursor-pointer"
                                    style="font-weight: 500;font-size:14px;">browse
                                    files</span>
                            </div>
                            <div class="secondary-text mt-10px fs-12px">Accepted file size should not exceed 20MB.
                            </div>
                            <div class="mat-error error-file-drop">
                            </div>
                        </div>
                    </div>
                    <div fxLayout="column" style="padding-top: 25px;" *ngIf="files.length > 0">
                        <div *ngFor="let item of files;let i=index">
                            <div fxLayout="row" style="padding-bottom:8px" layout-wrap>
                                <mat-icon style="font-size: 20px;" color="primary">description</mat-icon>
                                <span class="primary-color" style="font-size:14px; margin-right:8px"
                                    matTooltip="{{item.name}}">{{item.name | truncatedotted:[25]
                                    }}</span>&nbsp;
                                <span style="font-size:12px; margin-right: 6px;" class="tertiary-text">{{
                                    item.size/1024 |
                                    number:'1.0-0' }} kb</span>
                                <span style="flex:1 1"></span>
                                <span (click)="removeFile(files, i)" class="material-icons remove-file cursor-pointer"
                                    style="color:indianred;margin-right:10px">
                                    close
                                </span>
                            </div>
                        </div>
                    </div>
                    <div style="padding-bottom:16px;">
                    </div>
                </mat-card>
            </div>

#ts code

uploadFile(payload:any) {

    const formData: FormData = new FormData();

    this.files.map((file) => {
      formData.append('attachment', file, file.name);
    });

    this._inspectionService.uploadCSV(formData)
    .pipe(debounceTime(500))
    .subscribe(
      res=>{
        if(res.isSuccess){

        }  
      },
      err=>{
        AppUtils.errorHandler(err,this._notificationService, this.dialog);
      }
    )
  }

iterate through an array of image variables using wait() function [duplicate]

I’m trying to iterate through an array of images stored in variables using the wait() function. I want say a 2 second iteration through each. I had it working with Math.floor(Math.random) but want to try just iterating through each one individually using wait.

const [imgSrc, setImgSrc] = useState(tb);

  useEffect(() => {
    const wait = (time) => new Promise((resolve) => setTimeout(resolve, time));
    const interval = setInterval(() => {

      const images = [tb3, tb];
      
      for (let i = 0; i < images.length; i++) {
        
        setImgSrc(images[i]);
        wait(1000);
      }
    }, 2000);
    return () => clearInterval(interval);
  }, []);

How to define type with function overriding?

To give a little background i was initially facing this issue and as shared by the solution, it make sense to let the type to be flexible depending on the context

However, I found out that it isnt really working on my end

let timeoutId: null | ReturnType<typeof setTimeout> = null

timeoutId = setTimeout(...)

With the code above, i’m getting Type 'number' is not assignable to type 'Timeout'.ts(2322).

When I hover over timeoutId, I got let timeoutId: NodeJS.Timeout | null, while hovering over setTimeout, i see below

function setTimeout(handler: any, timeout?: any, ...args: any[]): number (+2 overloads)
namespace setTimeout

Is there any way to go about it? I think the root cause is due to function overriding

mockImplementationOnce() is not a function in second test suite?

I am currently testing something which uses http and I have run into something which I really can’t figure out.

The problem:
I import the http package, mock it, and then in my first test I mockImplementationOnce for it, it works fine. But when I do it in another test, it says TypeError: http.request.mockImplementationOnce is not a function.

The Code:
index.test.js

const http = require('http');

jest.mock('http');

describe('httpRequest', () => {
    // This test passes 
    test('gets response correctly', () => {
      http.request.mockImplementationOnce((opts, cb) => {
        // unrelated logic
      });

      const response = someFunctionCallingHttpRequest();

      expect(response).resolves.toBe('something')
    });

    test('handles something else correctly', () => {
      // This test throws an error here
      http.request.mockImplementationOnce((opts, cb) => {
        // unrelated logic
      });

      const response = someFunctionCallingHttpRequest();

      expect(response).resolves.toBe('something')
    });
  });

The error:
I get the following error in the second test suite

● httpRequest › handles something else correctly

TypeError: http.request.mockImplementationOnce is not a function

Any help would be really appreciated!

react throws ‘state update on unmounted component’ error on post request but not delete

I am building a react application using RTK Query. In the submit function of my dialog, upon POSTing a record I get the ‘trying to update state of an unmounted component error’. If I replace the POST mutation with a DELETE mutation for an arbitrary record the error goes away. The two requests both invalidate the same tags in question. I don’t need to set the state after the request- and can prevent the error with useRef which I understand… However I cannot understand why this error arises simply based on the request type being performed. Below is an example of the two different calls.

await addRecord({ string:'hello' }).unwrap()
await deleteRecord(1).unwrap()

How to make an outline around a single pixel on HTML5 Canvas similar to what’s seen on r/place

I’ve been trying to draw an outline around a single pixel on a canvas but I cant seem to get it right. Any idea’s how something like this is implemented on r/place. I read their article https://www.redditinc.com/blog/how-we-built-rplace but unfortunately no implementation details are there for the rectangle drawing. I’m guessing they did something clever with scaling.

Attached image below for reference.

enter image description here

How can I make the channel.send know where its being sent

I tried messing around with it and couldnt get it to work, all I want is for it to send in the channel that the user initiated the bot to talk

    // [beta]
    const storedBalances = await Users.findAll();
    storedBalances.forEach(b => currency.set(b.user_id, b));

    client.channels.fetch("/*the channel where channel.send will go to*/").then((c) => {
        channel = c;
    })
    console.log(`Logged in as ${client.user.tag}!`);
});```

Why does the constructor function not reset this field property? [duplicate]

I’m creating a simple game to practice using classes. In this game, the Game class should create a new instance of the Round class so that each round of the game start anew, with the default values for its fields and properties.

Problem

For some reason, new instances of the Round class after creating the original does not reset the roundOn property. Why doesn’t the constructor function in Round initialize this.roundOn = true for the second instance? Really stumped on what class behavior I’m overlooking.

It also doesn’t help to declare roundOn in the class body. Additionally, the Round constructor function does trigger as evidenced by the log statements.

MY CODE:

class Round {
  constructor () {
    console.log('-- constructor triggered! --')
    this.roundOn = true
  }

  changeVar () {
    this.roundOn = false
  }
}

class Game {
  constructor () {
    this.currentRound = new Round()
  }

  newRound () {
    this.currentRound = new Round()
  }
}

const currentGame = new Game()
const round = currentGame.currentRound
console.log('first instance:', round.roundOn)

round.changeVar()
console.log('after changeVar():', round.roundOn)

currentGame.newRound()
console.log('second instance (should be true):', round.roundOn)

OUTPUT:

-- constructor triggered! --
first instance: true
after changeVar(): false
-- constructor triggered! --
second instance (should be true): false

Is anyone aware of an issue with 3d transformations on the new Google Chrome version 100? [closed]

I am trying to use a matrix3d transformation that is working in firefox, but not in google chrome(version 100). I have tried a webkit like this:

document.getElementById(‘frontOfShip’).style.transition=’transform 3s’;
document.getElementById(‘frontOfShip’).style.webkitTransform=”matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,.58)”;
like this post,How to set the style -webkit-transform dynamically using JavaScript?, suggests.

The Element is not staying in place after the transformation, it snaps back to its original position. I did notice that the x and y values would work and the element stayed in place after the transformation as long as I don’t add a scaling factor.