Skip to content

Instantly share code, notes, and snippets.

@millermedeiros
Created September 26, 2012 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save millermedeiros/3788437 to your computer and use it in GitHub Desktop.
Save millermedeiros/3788437 to your computer and use it in GitHub Desktop.
amd-utils array methods to mimic ES6 Set
// how amd-utils Array methods can be used instead of the ES6 Set
// http://www.nczonline.net/blog/2012/09/25/ecmascript-6-collections-part-1-sets/
// http://millermedeiros.github.com/amd-utils/array.html
define(
[
'amd-utils/array/insert',
'amd-utils/array/remove',
'amd-utils/array/contains'
],
function (insert, remove, contains) {
var items = [];
insert(items, 5);
insert(items, "5");
insert(items, 5); // duplicate is ignored
console.log(items); // [5, "5"]
console.log( contains(items, 5) ); // true
remove(items, 5);
console.log( contains(items, 5) ); // false
console.log(items); // ["5"]
}
);
// If OOP is "your thing" it can be easily abstracted into a constructor
define(
[
'amd-utils/array/insert',
'amd-utils/array/remove',
'amd-utils/array/contains',
'amd-utils/array/forEach'
],
function (insert, remove, contains, forEach) {
function SetCollection(items){
this._items = [];
items.unshift(this._items);
insert.apply(null, items);
}
SetCollection.prototype = {
add : function(val){
insert(this._items, val);
},
// renamed `delete` to `remove` since `delete` is a bad name
remove : function(val){
remove(this._items, val);
},
has : function(val){
return contains(this._items, val);
},
size : function(){
return this._items.length;
},
// added `forEach` for convenience since `for` loops won't work
forEach : function(cb, thisObj){
forEach(this._items, cb, thisObj);
}
};
return SetCollection;
}
);
@millermedeiros
Copy link
Author

Used this gist to enhance my comment on Nicholas Zakas post: http://www.nczonline.net/blog/2012/09/25/ecmascript-6-collections-part-1-sets/#comment-17622

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment