Developing advanced generic functions in Typescript

I am currently working on a Hash Table implementation in Typescript with two separate functions, one to retrieve all keys and another to retrieve all values. Here is the code snippet I have so far:

  public values() {
    let values = new Array<T>();
    this._keyMap.forEach((element) =>
      element.forEach((innerElement) => values.push(innerElement.value))
    );
    return values;
  }

  public keys() {
    let values = new Array<string>();
    this._keyMap.forEach((element) =>
      element.forEach((innerElement) => values.push(innerElement.key))
    );
    return values;
  }

My goal now is to consolidate these two functions into one to avoid repetition of code. Ideally, I would like to be able to pass the type (for the array) as a parameter to the function. However, since one function requires pushing innerElement.value and the other innerElement.key, this presents a challenge. My desired outcome is something like:

  public values() {
    return getArrayInfo<T>(/*code to return value*/);
  }
  public keys() {
    return getArrayInfo<String>(/*code to return keys*/);
  }

 public getArrayInfo<I>(/*something*/) {
    let values = new Array<I>();
    this._keyMap.forEach((element) =>
      element.forEach((innerElement) => values.push(/*something*/))
    );
    return values;
  }

Answer №1

What you have is a good start. Utilizing property index signatures could enhance your code.

function getValues() {
    return retrieveArrayInfo<T>('value');
  }
  function getKeys() {
    return retrieveArrayInfo<String>('key');
  }

 function retrieveArrayInfo<I>(key: string) {
    let values = new Array<I>();
    this._keyMap.forEach((element) =>
      element.forEach((innerElement) => values.push(innerElement[key]))
    );
    return values;
  }

Keep in mind that this implementation might compromise type safety, so consider adding undefined/null checks for robustness.

Answer №2

After reviewing Tim B James' insights, I managed to devise a comprehensive TypeScript solution. For those who are curious, I have shared it below:

  enum searchType {
    identifier = 'identifier',
    data = 'data'
  }

  public fetchArrayData<I>(type: searchType) {
    let values = new Array<I>();
    this._keyMap.forEach((element) =>
      element.forEach((innerElement) =>
        values.push(innerElement[type.valueOf()])
      )
    );
    return values;
  }

  public dataValues() {
    return this.fetchArrayData<T>(searchType.data);
  }

  public dataIdentifiers() {
    return this.fetchArrayData<String>(searchType.identifier);
  }

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 save a scheduled cron reference in a database in order to deactivate it at a later time in a

I have implemented a system using cron to schedule push notifications. The user provides the push notification data and the scheduled time, and I use cron to send the notifications at the specified time. Below is the code snippet showing how I create a cr ...

retrieving form data from a submit button using objects in PHP

I am using objects to fetch a form (including a submit button) from another page. However, I am struggling to extract the POSTED information from that submit button and believe that AJAX might be necessary. Here is an example: Page 1 initiates a call to ...

Duplicate Key Error in MongoDB

I am currently developing a service that enables multiple events to store data on MongoDB. Each event creates new collections on MongoDB when it occurs, and if the same event needs to store different data, a new document in MongoDB is created. Below is th ...

Having trouble extracting a list of matches using a Regular Expression?

const stringWithDate: string = "4/7/20 This is a date!"; const reg: RegExp = new RegExp("^(\d{1,2}\/\d{1,2}\/\d{1,2})").compile(); const exist: boolean = reg.test(stringWithDate) const matches: RegExpExecArray | null = reg.exec(str ...

Encountering an issue in XtermJS where it is unable to read properties of undefined, specifically 'dimensions', while being used with NextJs version 14

UPDATE: Additional Details useEffect(() => { // let terminal; if (terminalRef.current) { const terminal = new Terminal({ fontFamily: "Menlo, Monaco, monospace", // fontSize: 12, // cursorBlink: true, ...

The controller is providing a null response following an ajax Post request

I am having trouble with my ajax Post request targeting the edit action method in my controller. The issue is that none of the values are being populated, they all come back as null. What should be happening is that when the '.save-user' button ...

Displaying 100,000 sprites with a faint 0.1 opacity, utilizing see-through backgrounds and crisp antialiasing

In my current setup, I have the following key pieces of code: Renderer renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, canvas: canvas }); Textures dot: THREE.ImageUtils.loadTexture('./assets/images/dot.png') Material ...

Error: Trying to access the 'map' property of a null value, Using ReactJS with Axios

I'm currently developing a search bar feature where the user can input their query, hit the search button, and the request is stored in search. This request is then sent via Axios and the results are displayed at the end. Everything seems to be workin ...

Oops! Looks like there's an issue with reading the property 'value' of undefined in React-typeahead

Having some issues with setting the state for user selection in a dropdown menu using the react-bootstrap-typeahead component. Any guidance or resources on this topic would be highly appreciated. Details can be found here. The function handleAddTask is su ...

Concealing and Revealing a Div Element in HTML

Every time the page is refreshed, I am encountering a strange issue where I need to double click a button in order to hide a block. Below is the code snippet for reference: <!DOCTYPE html> <html> <head> <meta name="viewport&quo ...

Steps for dynamically adjusting form fields depending on radio button selection

I am looking to create a dynamic form that changes based on the selection of radio buttons. The form includes textfields Field A, Field B, ..., Field G, along with radio buttons Radio 1 and Radio 2. I need to update the form dynamically depending on which ...

Customizing Geonames JSON Ajax Request

Having found the code I needed from a sample website, I am now seeking help to customize it to only display results from the USA. This is the current code snippet: $(function() { function log( message ) { $( "<div>" ).text( message ).pr ...

When resizing an anchor tag with a percentage in CSS, the child image width may not scale accordingly

In short, I have multiple draggable images on a map enclosed in anchor tags (<a><img></a>) to enable keyboard dragging. The original image sizes vary, but they are all too large, so I reduced them to 20% of their original sizes using the ...

jQuery function duplicates row in table

I am trying to utilize jQuery to generate a table, but I seem to be encountering an issue with my code: function showGrid(url, container, columns, page) { jQuery(container).empty(); var tr = jQuery("<tr class=\"mobileGridHeader\"> ...

I am encountering an issue where the useState hook is returning an undefined value on separate components, even after

When setting up a login context, I wrap all my routes with the context provider and pass the initial value using useState: <userContext.Provider value={{loggedUser, setLoggedUser}}> In LogInMenu.jsx, which is responsible for setting the loggedUser ( ...

Glitchy/Crazy CSS3 Animations

Currently, I am developing a website at . One of the features I have implemented is CSS3 transitions for route changes, but this feature only works in Chrome. Here's how the animation works: I apply the .preanimate class to rotate the phasing out di ...

Is there a more efficient alternative to `[].push.apply(this, arr)` for combining elements in an array instance within a constructor?

It only takes 0.15ms for this line in my constructor function to execute. [].push.apply(this, selector); I'm not satisfied with the 0.15ms execution time. I believe there must be a quicker alternative available. This particular line seems to be conv ...

Attempting to implement a smooth fade effect on my image carousel using React-Native

Struggling to animate this image carousel in reactNative and feeling lost. Despite reading the documentation on animations, I can't figure out how to implement it properly. My attempts keep resulting in errors. Any assistance would be greatly apprecia ...

Understanding how to utilize the scoped slot prop within a parent computed property

Currently, I have a closely connected pair of parent-child components utilizing a scoped slot. The child component sends data to the parent through a scoped slot prop (which we'll refer to as myScopedProp). Everything is functioning smoothly in this s ...

The conditional statement in EJS is not functioning properly

I have been incorporating the ejs template into my express application. Following the guidance on the official page of the template (https://www.npmjs.com/package/ejs), I am utilizing an if conditional to display a variable only if it has been defined. Her ...