public
Created

amd-utils array methods to mimic ES6 Set

  • Download Gist
Set.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
// 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;
 
}
);
functional.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
// 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"]
 
}
);

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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.