Skip to content

Instantly share code, notes, and snippets.

@emilbayes
Created March 24, 2015 21:52
Show Gist options
  • Select an option

  • Save emilbayes/6d8efb9ba5fdec35d061 to your computer and use it in GitHub Desktop.

Select an option

Save emilbayes/6d8efb9ba5fdec35d061 to your computer and use it in GitHub Desktop.
Capped Array with equivalent API to Array
'use strict';
/*
var a = cappedArray(3); //limited to 3 items
var b = cappedArray(1, 2, 3); //limited to 3 items, populated with [1, 2, 3]
a.concat(b, 10); //deepEqaul to `cappedArray(2, 3, 10);`
*/
module.exports = function cappedArray(size) {
var self = [];
if(arguments.length > 1) {
self = Array.prototype.slice.call(arguments);
self.size = arguments.length;
}
else
self.size = size;
self.push = function() {
var items = Array.prototype.slice.call(arguments);
Array.prototype.push.apply(self, items);
if(self.length > self.size) self.splice(0, self.length - size);
return self.length;
};
self.unshift = function() {
var items = Array.prototype.slice.call(arguments);
Array.prototype.unshift.apply(self, items);
if(self.length > self.size) self.splice(self.size, self.length - size);
return self.length;
};
self.concat = function() {
var arrays = Array.prototype.slice.call(arguments);
var c = cappedArray(self.size);
var curA;
do {
curA = Array.prototype.slice.call([].concat(arrays.shift()));
c.push.apply(c, [].concat(curA));
} while(arrays.length);
return c;
};
return self;
};
var assert = require('assert');
var cappedArray = require('./capped-array');
var a = cappedArray(3);
assert.strictEqual(a.size, 3);
a.push(10);
a.unshift(0);
assert.deepStrictEqual(Array.prototype.slice.call(a), [0, 10]);
var b = cappedArray(20, 30, 40);
assert.strictEqual(b.size, 3);
assert.deepStrictEqual(Array.prototype.slice.call(b), [20, 30, 40]);
var c = a.concat(b, 50, 60);
assert.strictEqual(c.size, a.size);
assert.deepStrictEqual(Array.prototype.slice.call(c), [40, 50, 60]);
c.push(80);
c.shift();
c.unshift(-10);
assert.deepStrictEqual(Array.prototype.slice.call(c), [-10, 60, 80]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment