Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the JavaScript equivalent to a C# HashSet?

I have a list of a few thousand integer keys. The only thing I need to do with this list is say whether or not a given value is in the list.

For C# I would use a HashSet to make that look-up fast. What's the JavaScript equivalent?


Minimal support level: IE 9+, jQuery (current)

like image 877
Jonathan Allen Avatar asked Jun 13 '14 00:06

Jonathan Allen


2 Answers

Actually JavaScript provides a Set object, fairly simple to use:

var set = new Set(); set.add(1); set.add(2);  set.has(1)    // true 

Unfortunately, it is not compatible with IE9.

like image 68
João Barbosa Avatar answered Sep 21 '22 15:09

João Barbosa


Under the hood, the JavaScript Object is implemented with a hash table. So, your Key:Value pair would be (your integer):true

A constant-time lookup function could be implemented as:

var hash = {   1:true,   2:true,   7:true   //etc... };  var checkValue = function(value){   return hash[value] === true; };   checkValue(7); // => true checkValue(3); // => false 
like image 32
LexJacobs Avatar answered Sep 19 '22 15:09

LexJacobs