9

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.

1 Answer 1

10

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'];
Sign up to request clarification or add additional context in comments.

4 Comments

I was going to comment on this exact thing. I just want to add that the Set class is just a data structure. Creating it yourself in Javscript is pretty trivial. I am fairly confused why this was asked lol
@Andy - For those of us spoiled on Java and the awesomeness that was the Java libraries and JavaDoc, the above is less than obvious. Its all about your perspective. (Something often not well understood on this message board <<No offense>>).
For a real set, this gets a little more complicated if the contents are objects that can't or shouldn't be converted to constant strings using Object.toString. In Python, I used set more than I used arrays, and I really miss it. I suppose that Python's sets aren't real sets either, they are hash tables implicitly indexed by the memory addresses of their values, but at least I didn't have to manage keys or hash functions myself. I still haven't found a solution that I really like.
The reason to use a library is so that you don't have to worry about implementation details and edge cases. Also there are nice-to-haves like Java's Set lets you know if the object you've added is already in the set or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.