Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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

Just to show that the ES6 Set can be easily replicated by using a helper library like amd-utils.

For now I will keep using plain arrays and the amd-utils array methods. Functional programming FTW.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.