Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java-style Set collection for Javascript

I need a Set that has the API similar to the Set in Java.

This implementation:

http://jsclass.jcoglan.com/set.html

Requires the use of RequireJS, which requires my Java brain to twist too much at the moment.

Posting a function that is the functionality for Set would be a great answer. Or a link to a Google Set or some other tech giant who has created this code already.

What about Google's Closure? The name confused me but it has a set.

like image 278
Guido Anselmi Avatar asked Nov 07 '13 01:11

Guido Anselmi


1 Answers

In my opinion whatever java.util.Set can achieve can be done using simple javascript object. I don't see why you need additional library:

// empty set
var basket = {};

// adding object to set    
basket['apple'] = true;
basket['banana'] = true;
basket['orange'] = true;
basket['apple'] = true;

// iterating through set contents, should print:
// apple
// banana
// orange
for(var fruit in basket)
  console.log(fruit);

// check if an element exist
if(basket['pineapple']) {
  console.log('has pineapple');
} else {
  console.log('no pineapple');
}

// remove element from set
delete basket['apple'];
like image 128
gerrytan Avatar answered Nov 03 '22 02:11

gerrytan