Created
September 26, 2012 14:40
-
-
Save millermedeiros/3788437 to your computer and use it in GitHub Desktop.
amd-utils array methods to mimic ES6 Set
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"] | |
} | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
); |
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
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.