Are there more efficient alternatives to utilizing arrays and index-based functions for storing in-memory data in TypeScript?

Is there a more efficient method for storing and retrieving data besides relying on Array index-based calls?

For instance:

export interface EntityInterface {
    id: number;
    name: string;
    age: number;
}

export class ClassName {
    entities: EntityInterface[] = [];

    temporaryIndex: number = 0;

    createEntity(name: string, age: number) {
        const temporaryId = ++this.temporaryIndex;

        this.entities.push({
            id: temporaryId,
            name: name,
            age: age
        });
    }

    getEntityById(id: number): number | undefined {
        const entityIndex = this.entities.findIndex((entity) => entity.id === id);
        if (entityIndex === -1) {
            return;
        }

        return entityIndex;
    }

    getEntityName(id: number): string | undefined {
        const index = this.getEntityById(id);
        if (! index) {
            return;
        }

        return this.entities[index].name;
    }
}

It's important to note that utilizing an external database isn't essential in this scenario since data loss upon application shutdown is not a concern.

Answer №1

When looking up a value by a numeric key in TypeScript (and consequently in JavaScript), it is advisable to utilize a data structure specifically designed for this purpose.

In plain JavaScript objects, this functionality is built-in; however, in TypeScript, you can define a numeric index signature for an object:

class ClassName {
    entities: { [k: number]: EntityInterface | undefined } = {};

    temporaryIndex: number = 0;

    createEntity(name: string, age: number) {
        const temporaryId = ++this.temporaryIndex;
        this.entities[temporaryId] = {
            id: temporaryId,
            name: name,
            age: age
        };
    }

    // the utility of this method is limited
    getEntityById(id: number): number | undefined {
        return this.entities[id] ? id : undefined
    }

    getEntityName(id: number): string | undefined {
        return this.entities[id]?.name;
    }
}

Alternatively, you can utilize a JavaScript Map, specifying that it holds EntityInterface values paired with number keys:

class ClassName {
    entities = new Map<number, EntityInterface>()

    temporaryIndex: number = 0;

    createEntity(name: string, age: number) {
        const temporaryId = ++this.temporaryIndex;
        this.entities.set(temporaryId, {
            id: temporaryId,
            name: name,
            age: age
        });
    }

    // the utility of this method is limited
    getEntityById(id: number): number | undefined {
        return this.entities.has(id) ? id : undefined
    }

    getEntityName(id: number): string | undefined {
        return this.entities.get(id)?.name;
    }
}

Both approaches yield similar results, especially when compared to iterating through an array. Refer to Map vs Object in JavaScript and the MDN documentation on Map vs Object for guidance on selecting the most suitable option.

In both implementations, the function getEntityById(id) now returns either the input or undefined, rendering it less useful. Instead, directly access this.entities using id as the key and handle a potentially undefined outcome.

Playground link to code

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

What is the best way to call an Angular component function from a global function, ensuring compatibility with IE11?

Currently, I am facing a challenge while integrating the Mastercard payment gateway api into an Angular-based application. The api requires a callback for success and error handling, which is passed through the data-error and data-success attributes of the ...

Navigating with multiple parameters in Angular 7 routing

I am currently facing an issue where I need to navigate to the same component with different parameters. Although I can subscribe to the params through the ActivatedRoute, I'm encountering a problem when trying to call router.navigate within the subsc ...

To enable the "Select All" functionality in ag-grid's infinite scrolling feature in Angular 4, utilize the header check box

Is there a way to add a checkbox in the header of ag-grid for selecting all options when using an infinite row model? It seems that the headerCheckboxSelection=true feature is not supported in this model. Are there any alternative methods to include a che ...

The color scheme detection feature for matching media is malfunctioning on Safari

As I strive to incorporate a Dark Mode feature based on the user's system preferences, I utilize the @media query prefers-color-scheme: dark. While this approach is effective, I also find it necessary to conduct additional checks using JavaScript. de ...

Module not found when attempting to import a newly created TypeScript module

A fresh Typescript project called puppeteer-jquery has just been released on the NPM registry. The code is functioning perfectly well. However, when attempting to integrate it into another project: npm install puppeteer-jquery and trying to import it lik ...

Angular, manipulating components through class references instead of creating or destroying them

I am exploring ways to move an angular component, and I understand that it can be achieved through construction and destruction. For example, you can refer to this link: https://stackblitz.com/edit/angular-t3rxb3?file=src%2Fapp%2Fapp.component.html Howeve ...

"Upon invoking the services provider in Ionic 2, an unexpected undefined value was

I encountered an issue while setting a value in the constructor of my page's constructor class. I made a call to the provider to fetch data. Within the service call, I was able to retrieve the data successfully. However, when I tried to access my vari ...

send mouse event to component when clicked

Looking to retrieve mouse coordinates in an Angular component. This is the HTML snippet: <div id="container" class="fullSize" style="height:100%;" (click)="onClick(ev)"></div> And here's the corresponding function in the TypeScript file ...

A versatile method for transforming enums into arrays that can handle null values

Looking for a simpler way to create a TypeScript function that converts an enum to an array, including support for null values. Here's an example of what I'm trying to achieve: enum Color { RED = "Red", GREEN = "Green&qu ...

Issue with cookies modification in Next.js 14 server actions

I'm currently facing a challenge while working on a Next.js 14 project where I am trying to make changes to cookies. Despite carefully following the Next.js documentation regarding server actions and cookie manipulation, I keep running into an error w ...

Is it possible to bind parameters in the select clause using TypeORM?

I'm currently working on implementing a search feature using the pg_trgm module in my PostgreSQL project built with TypeScript and TypeOrm. My SQL query that works for me looks like this: SELECT t, similarity(t, 'word') AS sml FROM test_t ...

During the compilation process, Angular could not locate the exported enum

In the file models.ts, I have defined the following enum: export enum REPORTTYPE { CUSTOMER, EMPLOYEE, PROJECT } After defining it, I use this enum inside another class like so: console.log(REPORTTYPE.CUSTOMER); When I save the file, the IDE automati ...

In relation to the characteristics of an Angular Component (written in TypeScript) Class

I am attempting to create a circle on a canvas using Angular. I have followed the necessary steps and have a basic understanding of how everything works. Although my IDE is not showing any errors, when I run the code, the console displays an error stating ...

Unexpected behavior observed in ng-select when pasting search values

When attempting to update an array of strings acting as the model for an ng-select, the values do not appear correctly in the search box. https://i.sstatic.net/WqdJ6.png The values that are displaying correctly are the ones selected from the dropdown men ...

What is the best way to terminate a Node.js app using a scheduler?

I've been attempting to halt my cron task and shut down the entire nodeapp after 5 executions, but despite trying various methods, all attempts have failed. The message "time to quit" continues to appear in the log every minute. What would be the mos ...

Error message in Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object.' NgFor is only able to bind to iterables like Arrays

When making an API call in my Angular project, I receive the following JSON response: { "data": { "success": true, "historical": true, "date": "2022-01-01", "base": "MXN&quo ...

Tips for interacting with the DOM in an Angular 4 application

I am trying to call the addItems method, but I keep getting an error: Uncaught TypeError: this.addItems is not a function Currently, I am using Angular 4 along with jQuery and the fullpage.js library. page-content.component.ts import { Component, OnI ...

implementing an event listener in vanilla JavaScript with TypeScript

Can anyone help me figure out how to correctly type my event listener in TypeScript + Vanilla JS so that it has access to target.value? I tried using MouseEvent and HTMLButtonElement, but I haven't been successful. const Database = { createDataKeys ...

NPM Package: Accessing resources from within the package

My Current Setup I have recently developed and published an npm package in typescript. This package contains references to font files located within a folder named public/fonts internally. Now, I am in the process of installing this package into an Angul ...

Tips for executing the JetBrains WebStorm refactoring tool 'modify ES6 import' for an entire project

Following a project refactor, certain files were relocated to a different npm package, leading to changes in source files to re-export them from their new location (in order to streamline the migration process). Later on, I came across a helpful refactori ...