Skip to content

Instantly share code, notes, and snippets.

@thebinarypenguin
Created July 27, 2013 22:55
Show Gist options
  • Save thebinarypenguin/6096610 to your computer and use it in GitHub Desktop.
Save thebinarypenguin/6096610 to your computer and use it in GitHub Desktop.
A "unique collection" object. Implemented as a node.js module.
var UniqueCollection = require('./UniqueCollection');
var testCollection = new UniqueCollection();
console.log('Create new collection');
console.log('Collection contents :', testCollection.list(), "\n");
var testItem = testCollection.add();
console.log('Add new item :', testItem);
console.log('Collection contents :', testCollection.list(), "\n");
console.log('Contains item '+testItem+' :', testCollection.contains(testItem));
console.log('Collection contents :', testCollection.list(), "\n");
console.log('Contains item FAKE :', testCollection.contains('FAKE'));
console.log('Collection contents :', testCollection.list(), "\n");
console.log('Remove item '+testItem+' :', testCollection.remove(testItem));
console.log('Collection contents :', testCollection.list(), "\n");
console.log('Remove item FAKE :', testCollection.remove('FAKE'));
console.log('Collection contents :', testCollection.list(), "\n");
/**
* A Unique Collection Object
* Items are alphanumeric strings (defined by createItem function)
* Items are 7 characters long (defined by itemLength variable)
*/
function UniqueCollection() {
var items = [];
var itemLength = 7;
/* Create a new item */
var createItem = function() {
var item = '';
var chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
for (var i=0; i<itemLength; i++) {
item += chars.charAt(Math.floor(Math.random() * chars.length));
};
return item;
};
/* Add a new item to the collection */
this.add = function() {
var item = createItem();
while (items.indexOf(item) !== -1) {
item = createItem();
}
items.push(item);
return item
};
/* Remove a specified item from the collection */
this.remove = function(item) {
var i = items.indexOf(item);
if (i === -1) {
return false;
} else {
items.splice(i, 1);
return true;
}
};
/* Check if a specified item is in the collection */
this.contains = function(item) {
var i = items.indexOf(item);
return (i === -1) ? false : true;
};
/* Return an array of all items in collection */
this.list = function() {
return items.slice();
};
}
module.exports = UniqueCollection;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment