Skip to main content
3 of 5
quoted problem description
t3chb0t
  • 44.3k
  • 9
  • 84
  • 190

TypeScript Generics: Create a generic map

Exercise from a TypeScript course:

Create a map using TypeScript Generics. The key is always a string.

The value can be a string or a number. It has to work with both types.

It's got to have the following methods:

  • Creating a new key-value pair : setItem(key: string, item: T)
  • Retrieving values : getItem(key: string)
  • Remove all items : clear()
  • Display all key-value items : printMap() "

Here my uncompiled TypeScript code:

// -- THE ACTUAL IMPLEMENTATION --------------------------
class GenericMap < T extends number | string > {
  private items: object[]

  constructor() {
    this.items = [];
  }

  setItem(key: string, item: T): void {
    let tmp = {};
    tmp[key] = item;

    this.items.push(tmp);
  }

  getItem(key: string): T {
    let ret = null;

    for (let i = 0; i < this.items.length; i++) {
      let curr = this.items[i];

      if (curr[key]) {
        return curr[key];
      }
    }

    return null;
  }

  clear() {
    this.items.length = 0;
  }

  printMap() {
    this.items.forEach((item) => {
      let key: string[] = Object.keys(item);

      console.log('{ "' + key[0] + '": ', item[key[0]], '}');
    });
  }
}

// ------- JUST TESTING --------------------
const numb = new GenericMap < number > ();
numb.setItem('alpha', 7);
numb.setItem('beta', 14);
numb.printMap();
numb.clear();
numb.printMap();

const strMap = new GenericMap < string > ();
strMap.setItem('color', 'Blue');
strMap.setItem('height', '54 cm');
strMap.printMap();
// ---------------------------------------------

The compiled code as a live-demo:

class GenMap {
  constructor() {
    this.items = [];
  }
  setItem(key, item) {
    let tmp = {};
    tmp[key] = item;
    this.items.push(tmp);
  }
  getItem(key) {
    let ret = null;
    for (let i = 0; i < this.items.length; i++) {
      let curr = this.items[i];
      if (curr[key]) {
        return curr[key];
      }
    }
    return null;
  }
  clear() {
    this.items.length = 0;
  }
  printMap() {
    this.items.forEach((item) => {
      let key = Object.keys(item);
      console.log('{ "' + key[0] + '": ', item[key[0]], '}');
    });
  }
}
const numb = new GenMap();
numb.setItem('alpha', 7);
numb.setItem('beta', 14);
numb.printMap();
numb.clear();
numb.printMap();
const strMap = new GenMap();
strMap.setItem('color', 'Blue');
strMap.setItem('height', '54 cm');
strMap.printMap();

It works fine. But I guess there a better ways to solve these exercise.

Especially my getItem-method has become rather long.

Has someone an idea to solve the exercise in a more elegant way?

What do you think about my idea of storing objects within an array?

Looking forward to reading your answers and comments.

michael.zech
  • 4.5k
  • 8
  • 33
  • 56