Skip to content

Instantly share code, notes, and snippets.

@icholy
Created August 23, 2012 21:12
Show Gist options
  • Save icholy/3441822 to your computer and use it in GitHub Desktop.
Save icholy/3441822 to your computer and use it in GitHub Desktop.
Javascript Collection idea

Example data

// example data
var data = [
  { uid: 1, foo: 435, bar: "435dsjkds6fd5" },
  { uid: 2, foo: 035, bar: "4adsf35asdf65" },
  { uid: 3, foo: 305, bar: "435ads6asdfd5" },
  { uid: 4, foo: 075, bar: "4fds35adsf6d5" },
  { uid: 5, foo: 165, bar: "43fd5f6dfadf5" },
];

The issue is that if I want to find object where uid = 2 I have to iterate.

for(var i=0;i<data.length;i++){
  if(data[i].uid == 2){
    // found it
  }
}

Use object/hash

var store = {}
data.forEach(function(item){ 
    acc[item.uid] = item; 
});

this gives us the benefit of fast lookups

store[2] => { uid: 2, foo: 035, bar: "4adsf35asdf65" }

but if we are interested in iterating we have to use a slow for in which is not ideal

Idea

this is what I hacked together

var Collection = function(prop){
  this.keyProperty = prop;
  this.content = {};
}

Collection.prototype = [];
Collection.prototype.constructor = Collection;

Collection.prototype.set = function(key, value){
  value[this.keyProperty] = key;
  this.content[key] = value;
  this.push(value);
};

Collection.prototype.unset = function(key){
  this.splice(this.indexOf(this.content[key]), 1);
  delete this.content[key];
};

Collection.prototype.add = function(value){
  this.content[value[this.keyProperty]] = value;
  this.push(value);
};

Collection.prototype.remove = function(value){
  delete this.content[value[this.keyProperty]];
  this.splice(this.indexOf(value), 1);
};

Usage

var store = new Collection("uid");
data.forEach(function(item){
    acc.add(item); 
});

// key lookups
console.log(store.content[2]) 
// => { uid: 2, foo: 035, bar: "4adsf35asdf65" }

// index lookups
console.log(store[3]) // => ?

// can still iterate quickly
store.forEach(function(item){
  console.log(item.bar);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment