Skip to content

Instantly share code, notes, and snippets.

@gurlock
Created August 19, 2017 19:27
Show Gist options
  • Save gurlock/e2bf9f51dd7e35e3b7aed9fba4ca7923 to your computer and use it in GitHub Desktop.
Save gurlock/e2bf9f51dd7e35e3b7aed9fba4ca7923 to your computer and use it in GitHub Desktop.
var LimitedArray = function(limit) {
var storage = [];
var limitedArray = {};
limitedArray.get = function(index) {
checkLimit(index);
return storage[index];
};
limitedArray.set = function(index, value) {
checkLimit(index);
storage[index] = value;
};
limitedArray.each = function(callback) {
for (var i = 0; i < storage.length; i++) {
callback(storage[i], i, storage);
}
};
var checkLimit = function(index) {
if (typeof index !== 'number') {
throw new Error('setter requires a numeric index for its first argument');
}
if (limit <= index) {
throw new Error('Error trying to access an over-the-limit index');
}
};
return limitedArray;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment