[JavaScript で色んなデータ構造(list/stack/queue/tree) http://c4se.hatenablog.com/entry/2012/01/28/190714 ]続き。単なるRingBufferとして、動的配列の用途には適しません。
/** * @fileOverView Simple RingBuffer class. * @author ne_Sachirou http://c4se.tk/profile/ne.html * @license 2012 Public Domain */ (function (global) { if (!Object.keys) { Object.keys = function (obj) { var result = [], key, i = 0; for (key in obj) { if (obj.hasOwnProperty(key)) { result[i] = key; i += 1; } } return result; }; } /** * @param {Object} target * @param {Object} source * @param {Boolean=false} does_overwrite */ function mixin (target, source, does_overwrite) { var keys = Object.keys(source), key, i = -1; while (key = keys[++i]) { if (does_overwrite || target[key] === void 0) { target[key] = source[key]; } } } mixin(global, { RingBuffer: RingBuffer, }); mixin(RingBuffer.prototype, { index: RingBuffer_index, forEach: RingBuffer_forEach }); /** * @class * Use reminder operator. * @param {Number=Ringbuffer1.INITIAL_SIZE} size * @property {Number} size */ function RingBuffer (size) { if (!(this instanceof RingBuffer)) {return new RingBuffer(size);} this.size = size || RingBuffer.INITIAL_SIZE; this.datas = new Array(this.size); } /**@constant*/ RingBuffer.INITIAL_SIZE = Math.pow(2, 8); /** * @param {Number} num * @return {Object} */ function RingBuffer_getIndex (num) { return this.datas[num % this.size]; } /** * @param {Number} num * @param {Object} data * @return {RingBuffer} this */ function RingBuffer_setIndex (num, data) { this.datas[num % this.size] = data; return this; } /** * Wrapper method of getIndex and setIndex. * @param {Number} num * @param {Object=undefined} data * @return {Object|RingBuffer} */ function RingBuffer_index (num, data) { console.log(this); if (data === void 0) { return RingBuffer_getIndex.call(this, num); } else { return RingBuffer_setIndex.call(this, num, data); } } /** * Enumrator * @param {Function} fun * fun(data, idx, this) * @param {Object} obj this in fun. * @return {Ringbuffer1} this */ function RingBuffer_forEach (fun, obj) { var datas = this.datas, data, i = -1; while (data = datas[++i]) { if (i in datas) { fun.call(obj, data, i, this); } } return this; } }(this));