Skip to content

Instantly share code, notes, and snippets.

@roundcorners
Created October 25, 2011 09:42
Show Gist options
  • Save roundcorners/1312056 to your computer and use it in GitHub Desktop.
Save roundcorners/1312056 to your computer and use it in GitHub Desktop.
Complex iterator object with helpers
var count = function(obj) {
var size = 0, key;
for (key in obj) {
size++;
}
return size;
};
var getItem = function(obj, i) {
var key, arr = [];
for (key in obj) {
arr.push(obj[key]);
}
return arr[i];
};
// Our iterator
var iterator = (function() {
var index = 0,
// Our data
data = {
fname: 'joe',
lname: 'chapman',
title: 'developer',
home: 'UK'
},
//data = ['joe', 'chapman', 'developer', 'UK'],
length = data.length ? data.length : count(data);
return {
next: function() {
if (!this.hasNext()) {
return null;
}
index = index + 1;
if (data[index] !== undefined) {
return data[index];
}
return getItem(data, index);
},
hasNext : function() {
return index < length-1;
},
current: function() {
if (data[index] !== undefined) {
return data[index];
}
return getItem(data, index);
},
end: function() {
if (data[length-1] !== undefined) {
return data[length-1];
}
return getItem(data, length-1);
},
reset: function() {
index = 0;
return this;
},
find: function(pos) {
if (data[pos] !== undefined) {
return data[pos];
}
return getItem(data, pos);
}
};
}());
var list = document.getElementById('list'),
data = [];
// Testing
data.push(iterator.current());
while(iterator.hasNext()) {
data.push("<li>" + iterator.next() + "</li>");
}
iterator.reset();
var custom = iterator.current() + ' ' + iterator.next() + ' is a ' + iterator.find(2) + ' living in the ' + iterator.end();
data.push(custom);
list.innerHTML = data.join('');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment