Is there a way to use Typescript.Collections.HashTable in my code?

I see the implementation of "HashTable" in the Typescript compiler code (in the src / compiler / core / hashTable.ts files).

Do you know that I can use it directly in a Typescript project?

+6
source share
3 answers

You can implement a very simple hash table where the key is a string, defining an interface

class Person { name: string; } interface HashTable<T> { [key: string]: T; } var persons: HashTable<Person> = {}; persons["bob"] = new Person(); var bob = persons["bob"]; 

It can only be used for string or number.

+13
source

Download the hashTable.ts file and place it right next to your file. Then at the top of the file do:

 ///<reference path='hashTable.ts' /> 

PS: I would recommend looking at the lib TypeScript Generic Collections I created. Here is an example dictionary:

 class Person { constructor(public name: string, public yearOfBirth: number,public city?:string) { } toString() { return this.name + "-" + this.yearOfBirth; // City is not a part of the key. } } class Car { constructor(public company: string, public type: string, public year: number) { } toString() { // Short hand. Adds each own property return collections.toString(this); } } var dict = new collections.Dictionary<Person, Car>(); dict.setValue(new Person("john", 1970,"melbourne"), new Car("honda", "city", 2002)); dict.setValue(new Person("gavin", 1984), new Car("ferrari", "F50", 2006)); console.log("Orig"); console.log(dict); // Changes the same john, since city is not part of key dict.setValue(new Person("john", 1970, "sydney"), new Car("honda", "accord", 2006)); // Add a new john dict.setValue(new Person("john", 1971), new Car("nissan", "micra", 2010)); console.log("Updated"); console.log(dict); // Showing getting / setting a single car: console.log("Single Item"); var person = new Person("john", 1970); console.log("-Person:"); console.log(person); var car = dict.getValue(person); console.log("-Car:"); console.log(car.toString()); 
+1
source

According to this blog post, TypeScript defines a Map interface that seems like a HashTable

other collections

  • Weakmap
  • Set
  • Weakset
+1
source

Source: https://habr.com/ru/post/953657/


All Articles