Skip to content

Instantly share code, notes, and snippets.

@mrlannigan
Created February 25, 2015 19:07
Show Gist options
  • Save mrlannigan/f8424ab8b63c1b600fb5 to your computer and use it in GitHub Desktop.
Save mrlannigan/f8424ab8b63c1b600fb5 to your computer and use it in GitHub Desktop.
ListBucket
var test = new ListBucket(4);
test.push(1);
test.push(2);
test.push(3);
test.push(4);
test.push(5);
test.push(6);
test.push(7);
test.push(8);
test.push(9);
test.push(1);
test.push(2);
test.push(3);
test.push(4);
test.push(5);
test.push(6);
test.push(7);
test.push(8);
test.push(9);
test.push(9);
console.log(test.toArray()); // [ 7, 8, 9, 9 ]
console.log(test); // { array: [ 8, 9, 9, 7 ], position: 3, size: 4, length: 4 }
'use strict';
function ListBucket(size) {
this.array = [];
this.position = 0;
this.size = size;
this.length = 0;
}
ListBucket.prototype.toArray = function () {
if (this.position === 0) {
return this.array.slice();
}
return this.array.slice(this.position, this.length).concat(
this.array.slice(0, this.position)
);
};
ListBucket.prototype.push = function (value) {
if (this.length < this.size) {
this.array.push(value);
this.length++;
this.position++;
return;
}
if (this.position >= this.length) {
this.position = 0;
this.array[this.position] = value;
this.position++;
return;
}
this.array[this.position] = value;
this.position++;
};
module.exports = ListBucket;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment