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

Issues may arise in TypeScript when you are working with an array of objects along with other properties within a type

I am encountering an issue with an object structure similar to the one below: let Obj = { ['0'] : { mode: 'x' }, getMode: () => 'x' } The problem arises when I attempt to create a type definition as shown here: type Obj = ...

Issue with Angular 4 Routing: Links are opening in new window instead of within router-outlet

I am currently facing an issue while trying to display the SuburbDataComponent HTML on the DASHBOARD-SIDE-PANEL-COMPONENT.HTML. When I click on Dashboard, it opens a new window but only displays the SuburbDataComponent.html without showing the side panel ...

Alter the navigation but keep the URL intact without modifying the view

I have an Angular project that includes a login component. The login component is located in the directory app/main/login. I am trying to navigate to the login component from app.component.html using a button. Below is the code snippet from my app-routi ...

What are the best ways to troubleshoot my Angular 2 project?

I've been searching for my TypeScript files in the console, but they're not showing up. I've tried everything to debug my Angular 2 project, but no luck. I can't move forward without debugging, can anyone lend a hand? ...

What methods can be used to test scss subclasses within an Angular environment?

Exploring different background colors in various environments is a task I want to undertake. The environments include bmw, audi, and vw, with each environment having its own unique background color. Need help writing an Angular test for this? How can I mod ...

What is the correct way to import scss files in a Next.js project?

Currently, I am working on a NextJS project that uses Sass with TypeScript. Everything is running smoothly in the development environment, but as soon as I attempt to create a build version of the project, I encounter this error. https://i.stack.imgur.com ...

Is there a way to apply a decorator to a function that has been returned?

Can the following be accomplished? bar () { @custom yield () => { } } ...

Display the chosen HTML template in real-time

Recently, I started using Angular 2 and encountered an issue that I need help with. 1] I have created 2-3 templates for emails and SMS that will display predefined data. 2] I have also designed a screen with a dropdown menu containing options like email ...

Encountering Typescript errors while compiling an Angular module with AOT enabled

I am currently in the process of manually constructing an Angular module with Webpack, opting not to use the CLI. While a normal build is functioning without any issues, encountering errors during an AOT build! Here's how my tsconfig.aot.json file ...

Once the Angular project has been initialized, the Button disable attribute cannot be modified

In my Ionic-Angular project, I am creating registration pages where users input their information in multiple steps. For each step, there is a button that remains disabled until the correct information is entered. An issue arises when transitioning to the ...

Creating multilingual menus with ABP and Nebular

Currently, I am in the process of developing an application using ABP framework version 4.4 and integrating the Nebular theme as opposed to the default basic theme. Amidst various challenges faced during this migration, one particular issue stands out - lo ...

Angular2 Error: Issue with the "match" function in JavaScript

Why am I receiving a typeerror that says "cannot read property of 'match' undefined"? var numInput = document.getElementById('input'); // Listen for input event on numInput. numInput.addEventListener('input', function(){ ...

Typescript Routing Issue - This call does not match any overloads

Need assistance with redirecting to a sign-up page upon button click. Currently encountering a 'no overload matches this call' error in TypeScript. Have tried researching the issue online, but it's quite broad, and being new to Typescript ma ...

Inside the function() in angular 2, the value of 'this' is not defined

I've integrated a UIkit confirmation modal into my app. However, I'm encountering an issue when trying to click the <button> for confirmation. The this inside the function is showing up as undefined. Here's the snippet of code in quest ...

Utilizing the split function within an ngIf statement in Angular

<div *ngIf="store[obj?.FundCode + obj?.PayWith].status == 'fail'">test</div> The method above is being utilized to combine two strings in order to map an array. It functions correctly, however, when attempting to incorporate the spli ...

It appears that protractor-flake is programmed to re-run all tests instead of just the ones that have failed

Running tests using the latest version of "[email protected]", encountering failures during testing but the tests are rerunning again. No custom reporter used except Allure reporting. Below is the command used for running: protractor-flake --max-at ...

You must provide a secret or key in order to use the JwtStrategy

I have encountered the following error and I am unsure of its cause. Can you assist me? ERROR [ExceptionHandler] JwtStrategy requires a secret or key TypeError: JwtStrategy requires a secret or key at new JwtStrategy (C:\Users\wapg2\OneDriv ...

Relaying numerous references in TypeScript

Having some trouble forwarding an object of refs in TypeScript and struggling with how to properly type them. Here are the refs and the way I'm passing them into my component. const storyRef = useRef<HTMLElement>(null); const parcoursRef = useR ...

Creating nested return types: A guide to defining function return types within a Typescript class

My large classes contain functions that return complex objects which I am looking to refactor. class BigClass { ... getReferenceInfo(word: string): { isInReferenceList:boolean, referenceLabels:string[] } { ... } } I am considering somethi ...

What is the reason behind TypeScript failing to provide type safety in a generic higher order component which introduces extra properties into React components?

I'm currently working on developing a versatile higher order component, but have encountered an issue with type safety not being enforced. Interestingly, when attempting the same implementation without using generics, the type safety is verified as ex ...