Invoke the method saved as a class attribute

Within my codebase, there exists a class named Process. This class has a constructor that takes in a type of object () => void. Initially, everything seemed to be working perfectly fine when I passed this object into the class. However, issues arose when I tried to call it from a singleton object called "Kernel." The Kernel iterates over all the Process[] objects stored within my Scheduler class. How can I correctly invoke this function? Additionally, is there a way to make the function in the Process class capable of accepting other types of functions with arguments without adding extra properties?

Process

export class Process {
    id: Id<Process>
    run: () => void
    cpuUsed?: number
    priority: ProcessPriority

    constructor(id: Id<Process>, priority: ProcessPriority, task: () => void) {
        this.id = id
        this.priority = priority
        this.run = task
    }
}

Kernel

The primary purpose of the Kernel object is to manage how often tasks added to the scheduler are executed. I anticipate that the executeTasks() function will correctly trigger the .run() method stored in the map retrieved from the scheduler.

export class Kernel implements ITaskManager {
    private static _instance?: Kernel
    static getInstance() {
        if (this._instance) return this._instance
        return this._instance = new Kernel()
    }

    scheduler: Scheduler

    executeTasks() {
        console.log("Task count: " + this.scheduler.taskQueue.size)
        for(const value in Array.from(this.scheduler.taskQueue.keys())) {
            let task = this.scheduler.taskQueue.get(value as Id<Process>)
            task?.run()
        }
    }

    kill(): void {
        throw new Error("Method not implemented.")
    }

    pause(): void {
        throw new Error("Method not implemented.")
    }

    skip(): void {
        throw new Error("Method not implemented.")
    }

    constructor() {
        console.log("Constructed scheduler.")
        this.scheduler = new Scheduler()
    }
}

Scheduler

This section contains the function that I'm attempting to invoke. For testing and brevity purposes, I've set it up to add a new instance of Process in the constructor. This approach helps me confirm that I am doing it correctly.

export class Scheduler {
    taskQueue: Map<Id<Process>, Process>

    constructor() {
        this.taskQueue = new Map()
        let tempProcess = new Process("someID" as Id<Process>, ProcessPriority.INDIFFERENT, this.someFunction)
        this.addTask(tempProcess)
    }

    // This is the function I'm trying to call.
    someFunction = function(): void {
        console.log("It kinda works.")
    }

    addTask(task: Process) {
        console.log("adding task: " + task.id + " | " + task)
        this.taskQueue.set(task.id, task)
    }

    getTask(id: Id<Process>): Process | undefined{
        return this.taskQueue.get(id)
    }
}

Answer №1

The issue arose from the function executeTasks(). It was mishandling the iteration over the map, leading to unexpected results. The proper way to iterate over a map is as follows. Instead of getting a key value of 0, it should have returned "someID".

for (let [, value] of this.scheduler.taskQueue) {
    value.run()
}

// Alternatively

this.scheduler.taskQueue.forEach(task => task.run())

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using a static class reference as a parameter in a generic type leads to a error

Before I submit a ticket on github, I want to double-check that I'm not making any mistakes. The issue should be clear enough: class A {} class B { static A = A; } function foo<T>(arg: T) {} // this is valid const b = new B.A; // "B" only ...

"Implementing a Filter for Selecting Multiple Options in Ionic Framework

I need help with filtering books in an online library project using a modal page. The modal has 3 input fields for title, author, and year. How can I filter the books based on these inputs? Here is a snippet of my modal.html code: <ion-content pa ...

Enhance the aesthetic appeal of the imported React component with added style

I need assistance with applying different styles to an imported 'notification' component within my header component. The notification component has its own CSS style, but I want to display it in the header component with unique styling. How can I ...

Locate a class using an interface

Consider the code snippet below: interface FirstInterface {} interface SecondInterface {} interface ThirdInterface {} class TheClass { constructor(howdy: FirstInterface) {} } class Foo implements FirstInterface {} class Bar implements SecondInterface ...

Enhancements to a NativeScript Application

After running some tests on my NativeScript app following the steps outlined here - , I found that it takes 18 seconds for the program to start and for a user to log in. Is this considered acceptable performance? Appreciate any feedback provided! ...

When I attempt to conceal the filter within mat-table using *ngIf, I encounter an issue where I am unable to read the property 'value' due to it being

After creating a mat-table, I encountered an issue when trying to show and hide my input filter area using a button. If I use *ngIf="showInputFilter" to hide the filter area, I receive the error message Cannot read property 'value' of u ...

What is the equivalent of html script tags in Webpack 2?

I recently downloaded a new npm module that suggests including the following code in my project: <link href="node_modules/ng2-toastr/bundles/ng2-toastr.min.css" rel="stylesheet" /> <script src="node_modules/ng2-toastr/bundles/ng2-toastr.min.js"&g ...

Why is it that in reactive forms of Angular, the parameter being passed in formControlName is passed as a string?

I am currently working on a reactive form in Angular. In order to synchronize the FormControl object from the TypeScript file with the form control in the HTML file, you need to utilize the formControlName directive. This is accomplished as shown below: f ...

What is the process for importing a function dynamically in a Next.js TypeScript environment?

Currently, I am utilizing a React modal library known as react-st-modal, and I am attempting to bring in a hook named useDialog. Unfortunately, my code is not functioning as expected and appears like this: const Dialog = dynamic<Function>( import(& ...

Having difficulty ensuring DayJs is accessible for all Cypress tests

Currently embarking on a new Cypress project, I find myself dealing with an application heavily focused on calendars, requiring frequent manipulations of dates. I'm facing an issue where I need to make DayJs globally available throughout the entire p ...

Leveraging the power of APIs to bring in the Chicago Art Institute into a React TypeScript

Struggling to import a list of image details from the Chicago Art Institute into my React application. I need help understanding APIs, so a detailed answer would be appreciated. I have the code for the image list but can't figure out how to make it wo ...

Using TypeScript to pass the text field ID to a function for clearing the text field with a button

I am looking for a way to improve the functionality of my web page featuring several buttons that will clear different text boxes on the same line. Currently, I am using separate functions for each button, but my goal is to streamline this process by utili ...

Issue encountered while managing login error messages: http://localhost:3000/auth/login net::ERR_ABORTED 405 (Method Not Allowed)

I am working on the /app/auth/login/route.ts file. import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs' import { cookies } from 'next/headers' import { NextResponse } from 'next/server' export async functi ...

Issue with updating initial state that is null in Redux Toolkit

Encountered an issue while using Redux Toolkit with Redux Persist. Unable to update the initial state of a user if it's null. The code consistently assigns null to the store regardless of passing parameters. import { createSlice, PayloadAction } from ...

Steer clear from using the implicit 'any' type while utilizing Object.keys in Typescript

I have a unique situation where I need to loop over an Object while maintaining their type without encountering the error "Element implicitly has an 'any' type because 'ContactList' has no index signature". Despite extensive discussion ...

"Setting Up a Service in Angular: A Step-by-Step Guide

I am facing an issue with a root service that contains composition within it, as shown below: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class MapService { private rmap: RMap; ini ...

Vitest surpasses Jest by providing explicit type declarations, ensuring no more "unknown type" errors

Transitioning from Jest to vitest has been a smooth process for me. I'm currently in the midst of converting the following code snippets: // Jest const myLib = jest.requireActual("mylib.js") to this: // Vitest const myLib = await vi.importA ...

Ways to enable Urql (typescript) to accept Vue reactive variables for queries generated using graphql-codegen

I'm currently developing a Vue project that involves using urql and graphql-codegen. When utilizing useQuery() in urql, it allows for the use of Vue reactive variables to make the query reactive and update accordingly when the variables change. The ...

Leverage server-side data processing capabilities in NuxtJS

I am currently in the process of creating a session cookie for my user. To do this, I send a request to my backend API with the hope of receiving a token in return. Once I have obtained this token, I need to store it in a cookie to establish the user' ...

Obtaining Input Field Value in Angular Using Code

How can I pass input values to a function in order to trigger an alert? Check out the HTML code below: <div class="container p-5 "> <input #titleInput *ngIf="isClicked" type="text" class="col-4"><br& ...