Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashset in TypeScript

Tags:

I am attempting to do something very basic in TypeScript. Get a list of unique strings while parsing a map as referenced in this post.

Here is what I am attempting to do:

let myData = new Array<string>();
for (let myObj of this.getAllData()) {
    let name = myObj.name;
    console.log("## we have " + name);
    console.log("### is property ? " + myData.hasOwnProperty(name));
    if (!myData.hasOwnProperty(name)){
        myData.push(name);
    }
}

My printout will always evaluate to false for any string, duplicate or not. Here is some sample output:

 ## we have COW
 ### is property ? false
 ## we have COW
 ### is property ? false
 ## we have RAODN
 ### is property ? false
 ## we have COOL
 ### is property ? false

However, when the process completes, my list contain duplicates. I have tried looking at this documentation, but there is no mention of a 'hashset' or any set in general.

Is there something equivalent in TypeScript of a Set? i.e A list of unique elements

like image 961
angryip Avatar asked Oct 21 '16 15:10

angryip


People also ask

Is there a set in TypeScript?

TypeScript set is a new data structure added in ES6 version of JavaScript. It allows us to store distinct data (each value occur only once) into the List similar to other programming languages. Sets are a bit similar to maps, but it stores only keys, not the key-value pairs.

How do you set values in TypeScript?

The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. Declare its type and value in one statement.

How do I create an empty set in TypeScript?

type emptySet = void; let es: emptySet = null; There is also the never type, which doesn't accept anything, even null .

What is set in angular?

Sets are a bit like maps but they only store keys not key-value pairs. They are common in other programming languages but are a new addition to JavaScript in ES 6.


2 Answers

It exists!

mySet: Set<string> = new Set<string>();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

like image 80
Marcel Avatar answered Sep 20 '22 21:09

Marcel


An object {} is a key value pair dictionary is a hash set in JavaScript which TypeScript is a superset of and therefore you can use a JS object to serve in this role.

A quick version from the code you posted:

let myData = {};
for (let myObj of this.getAllData()) {
    let name = myObj.name;
    if (!myData[name]){
        myData[name] = name;
    }
}
like image 44
silentsod Avatar answered Sep 20 '22 21:09

silentsod