Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over a Set in TypeScript?

Tags:

typescript

How do you iterate over a set in TypeScript? for..of does not work:

'Set<string>' is not an array type or a string type 

.forEach is not acceptable, because it hides this. I'd prefer not to do a while loop in a try catch block. What am I missing? It can't it possibly so clumsy as to require try {while} catch {}.

like image 380
Programmer9000 Avatar asked Feb 04 '16 05:02

Programmer9000


People also ask

How do I iterate through a TypeScript set?

Use the forEach() method to iterate over a Set in TypeScript. The forEach method takes a function that gets invoked once for each value in the Set object. The forEach method returns undefined . Copied!

Can we iterate over set in JavaScript?

You can iterate through the elements of a set in insertion order.

How do I loop a list in TypeScript?

TypeScript includes the for...of loop to iterate and access elements of an array, list, or tuple collection. The for...of loop returns elements from a collection e.g. array, list or tuple, and so, there is no need to use the traditional for loop shown above.

What is an iterable in TypeScript?

Iterables. An object is deemed iterable if it has an implementation for the Symbol. iterator property. Some built-in types like Array , Map , Set , String , Int32Array , Uint32Array , etc. have their Symbol. iterator property already implemented.


2 Answers

@SnareChops was mostly correct:

mySet.forEach(function(item){     // do something with "this" }, **this**); 

This works.

I'm guessing:

for(item of mySet.values()){ } 

Would work if I weren't working with es-shim stuff which is messing everything up for me. But the shim stuff is prescribed by the Angular 2 crew so ¯_(ツ)_/¯

The only other thing that worked was:

for (var item of Array.from(set.values())) { } 

or something like that, which is just terrible.

like image 108
Programmer9000 Avatar answered Oct 01 '22 06:10

Programmer9000


You can still use .forEach with the correct this by using a regular function instead of an arrow function

mySet.forEach(function(item){     expect(this).toEqual(item); }); 

Compared to

class MyClass{     ...     doSomething():{         mySet.forEach((item) => {             expect(this instanceof MyClass).toEqual(true);         });     } } 

Another way to iterate is to use a for loop over the values

for(item of mySet.values()){     ... } 

More information on iterating Set with foreach can be found here

like image 39
SnareChops Avatar answered Oct 01 '22 07:10

SnareChops