Icaro
Icaro

Reputation: 14845

Creating (even more generics) functions in Typescript

I am creating a simple hash table in Typescript and I have two functions, one that return all keys and another one that return all values, and I got something like this:

  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;
  }

What I am trying to do know is to condense this two functions into one as much of the code is repetition, I would only have to pass the type to the functions (for the array) what is easy however for one I need to push innerElement.value and for the other innerElement.key so hopefully I would have 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;
  }

Upvotes: 1

Views: 35

Answers (2)

Icaro
Icaro

Reputation: 14845

Based on Tim B James response I was able to come up with a solution that fully uses typescript, I posted it here in case some is interested:

  enum typeOfSearch {
    key = 'key',
    value = 'value'
  }

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

  public values() {
    return this.getArrayInfo<T>(typeOfSearch.value);
  }

  public keys() {
    return this.getArrayInfo<String>(typeOfSearch.key);
  }

Upvotes: 1

Tim B James
Tim B James

Reputation: 20364

What you have is pretty close to something. You could use property index signatures.

public values() {
    return getArrayInfo<T>('value');
  }
  public keys() {
    return getArrayInfo<String>('key');
  }

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

However with this you will lose a lot of type safety, and you would probably want to add some undefined/null checking in the mix.

Upvotes: 1

Related Questions