@stdlib/dstructs-circular-buffer 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/main.js ADDED
@@ -0,0 +1,453 @@
1
+ /**
2
+ * @license Apache-2.0
3
+ *
4
+ * Copyright (c) 2018 The Stdlib Authors.
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ /* eslint-disable no-restricted-syntax, no-invalid-this */
20
+
21
+ 'use strict';
22
+
23
+ // MODULES //
24
+
25
+ var isCollection = require( '@stdlib/assert-is-collection' );
26
+ var isPositiveInteger = require( '@stdlib/assert-is-positive-integer' ).isPrimitive;
27
+ var isNonNegativeInteger = require( '@stdlib/assert-is-nonnegative-integer' ).isPrimitive;
28
+ var setReadOnly = require( '@stdlib/utils-define-nonenumerable-read-only-property' );
29
+ var setReadOnlyAccessor = require( '@stdlib/utils-define-nonenumerable-read-only-accessor' );
30
+ var iteratorSymbol = require( '@stdlib/symbol-iterator' );
31
+ var MAX_ITERATIONS = require( '@stdlib/constants-float64-max' );
32
+ var arraylike2object = require( '@stdlib/array-base-arraylike2object' );
33
+ var format = require( '@stdlib/string-format' );
34
+
35
+
36
+ // MAIN //
37
+
38
+ /**
39
+ * Circular buffer constructor.
40
+ *
41
+ * @constructor
42
+ * @param {(PositiveInteger|Collection)} buffer - buffer size or an array-like object to use as the underlying buffer
43
+ * @throws {TypeError} must provide either a valid buffer size or an array-like object
44
+ * @returns {CircularBuffer} circular buffer instance
45
+ *
46
+ * @example
47
+ * var b = new CircularBuffer( 3 );
48
+ *
49
+ * // Fill the buffer...
50
+ * var v = b.push( 'foo' );
51
+ * // returns undefined
52
+ *
53
+ * v = b.push( 'bar' );
54
+ * // returns undefined
55
+ *
56
+ * v = b.push( 'beep' );
57
+ * // returns undefined
58
+ *
59
+ * // Add another value to the buffer and return the removed element:
60
+ * v = b.push( 'boop' );
61
+ * // returns 'foo'
62
+ */
63
+ function CircularBuffer( buffer ) {
64
+ var buf;
65
+ var i;
66
+ if ( !(this instanceof CircularBuffer) ) {
67
+ return new CircularBuffer( buffer );
68
+ }
69
+ if ( isPositiveInteger( buffer ) ) {
70
+ buf = [];
71
+ for ( i = 0; i < buffer; i++ ) {
72
+ buf.push( 0.0 ); // initialize with zeros, but could be any value (we're just ensuring a contiguous block of memory)
73
+ }
74
+ } else if ( isCollection( buffer ) ) {
75
+ buf = buffer;
76
+ } else {
77
+ throw new TypeError( format( 'invalid argument. Must provide either a valid buffer size (i.e., a positive integer) or an array-like object which can serve as the underlying buffer. Value: `%s`.', buffer ) );
78
+ }
79
+ this._buffer = arraylike2object( buf );
80
+ this._length = buf.length;
81
+ this._count = 0;
82
+ this._i = -1;
83
+ return this;
84
+ }
85
+
86
+ /**
87
+ * Clears the buffer.
88
+ *
89
+ * @name clear
90
+ * @memberof CircularBuffer.prototype
91
+ * @type {Function}
92
+ * @returns {CircularBuffer} circular buffer instance
93
+ *
94
+ * @example
95
+ * var b = new CircularBuffer( 2 );
96
+ *
97
+ * // Add values to the buffer:
98
+ * b.push( 'foo' );
99
+ * b.push( 'bar' );
100
+ * b.push( 'beep' );
101
+ * b.push( 'boop' );
102
+ *
103
+ * // Get the number of elements currently in the buffer:
104
+ * var n = b.count;
105
+ * // returns 2
106
+ *
107
+ * // Clear the buffer:
108
+ * b.clear();
109
+ *
110
+ * // Get the number of buffer values:
111
+ * n = b.count;
112
+ * // returns 0
113
+ */
114
+ setReadOnly( CircularBuffer.prototype, 'clear', function clear() {
115
+ this._count = 0;
116
+ this._i = -1; // this ensures that we always fill the buffer starting at index `0`.
117
+ return this;
118
+ });
119
+
120
+ /**
121
+ * Number of elements currently in the buffer.
122
+ *
123
+ * @name count
124
+ * @memberof CircularBuffer.prototype
125
+ * @readonly
126
+ * @type {NonNegativeInteger}
127
+ *
128
+ * @example
129
+ * var b = new CircularBuffer( 4 );
130
+ *
131
+ * // Get the value count:
132
+ * var n = b.count;
133
+ * // returns 0
134
+ *
135
+ * // Add values to the buffer:
136
+ * b.push( 'foo' );
137
+ * b.push( 'bar' );
138
+ *
139
+ * // Get the value count:
140
+ * n = b.count;
141
+ * // returns 2
142
+ */
143
+ setReadOnlyAccessor( CircularBuffer.prototype, 'count', function get() {
144
+ return this._count;
145
+ });
146
+
147
+ /**
148
+ * Boolean indicating whether a circular buffer is full.
149
+ *
150
+ * @name full
151
+ * @memberof CircularBuffer.prototype
152
+ * @readonly
153
+ * @type {boolean}
154
+ *
155
+ * @example
156
+ * var b = new CircularBuffer( 3 );
157
+ *
158
+ * // Determine if the buffer is full:
159
+ * var bool = b.full;
160
+ * // returns false
161
+ *
162
+ * // Add values to the buffer:
163
+ * b.push( 'foo' );
164
+ * b.push( 'bar' );
165
+ * b.push( 'beep' );
166
+ * b.push( 'boop' );
167
+ *
168
+ * // Determine if the buffer is full:
169
+ * bool = b.full;
170
+ * // returns true
171
+ */
172
+ setReadOnlyAccessor( CircularBuffer.prototype, 'full', function get() {
173
+ return this._count === this._length;
174
+ });
175
+
176
+ /**
177
+ * Returns an iterator for iterating over a circular buffer.
178
+ *
179
+ * ## Notes
180
+ *
181
+ * - An iterator does not iterate over partially full buffers.
182
+ *
183
+ * @name iterator
184
+ * @memberof CircularBuffer.prototype
185
+ * @type {Function}
186
+ * @param {NonNegativeInteger} [niters] - number of iterations
187
+ * @throws {TypeError} must provide a nonnegative integer
188
+ * @returns {Iterator} iterator
189
+ *
190
+ * @example
191
+ * var b = new CircularBuffer( 3 );
192
+ *
193
+ * // Add values to the buffer:
194
+ * b.push( 'foo' );
195
+ * b.push( 'bar' );
196
+ * b.push( 'beep' );
197
+ * b.push( 'boop' );
198
+ *
199
+ * // Create an iterator:
200
+ * var it = b.iterator( b.length );
201
+ *
202
+ * // Iterate over the buffer...
203
+ * var v = it.next().value;
204
+ * // returns 'bar'
205
+ *
206
+ * v = it.next().value;
207
+ * // returns 'beep'
208
+ *
209
+ * v = it.next().value;
210
+ * // returns 'boop'
211
+ *
212
+ * var bool = it.next().done;
213
+ * // returns true
214
+ */
215
+ setReadOnly( CircularBuffer.prototype, 'iterator', function iterator( niters ) {
216
+ var iter;
217
+ var self;
218
+ var FLG;
219
+ var N;
220
+ var n;
221
+ var i;
222
+
223
+ if ( arguments.length ) {
224
+ if ( !isNonNegativeInteger( niters ) ) {
225
+ throw new TypeError( format( 'invalid argument. Must provide a nonnegative integer. Value: `%s`.', niters ) );
226
+ }
227
+ N = niters;
228
+ } else {
229
+ N = MAX_ITERATIONS;
230
+ }
231
+ self = this;
232
+
233
+ // Initialize the iteration index and counter:
234
+ i = this._i;
235
+ n = 0;
236
+
237
+ // Create an iterator protocol-compliant object:
238
+ iter = {};
239
+ setReadOnly( iter, 'next', next );
240
+ setReadOnly( iter, 'return', end );
241
+ if ( iteratorSymbol ) {
242
+ setReadOnly( iter, iteratorSymbol, factory );
243
+ }
244
+ return iter;
245
+
246
+ /**
247
+ * Returns an iterator protocol-compliant object containing the next iterated value.
248
+ *
249
+ * @private
250
+ * @returns {Object} iterator protocol-compliant object
251
+ */
252
+ function next() {
253
+ /* eslint-disable no-underscore-dangle */
254
+ n += 1;
255
+ if ( FLG || n > N ) {
256
+ return {
257
+ 'done': true
258
+ };
259
+ }
260
+ // If the buffer is only partially full, don't allow iteration over "undefined" elements (this ensures similar behavior with `toArray()`)...
261
+ if ( self._count !== self._length ) {
262
+ FLG = true;
263
+ return {
264
+ 'done': true
265
+ };
266
+ }
267
+ i = (i+1) % self._length;
268
+ return {
269
+ 'value': self._buffer.accessors[ 0 ]( self._buffer.data, i ),
270
+ 'done': false
271
+ };
272
+
273
+ /* eslint-enable no-underscore-dangle */
274
+ }
275
+
276
+ /**
277
+ * Finishes an iterator.
278
+ *
279
+ * @private
280
+ * @param {*} [value] - value to return
281
+ * @returns {Object} iterator protocol-compliant object
282
+ */
283
+ function end( value ) {
284
+ FLG = true;
285
+ if ( arguments.length ) {
286
+ return {
287
+ 'value': value,
288
+ 'done': true
289
+ };
290
+ }
291
+ return {
292
+ 'done': true
293
+ };
294
+ }
295
+
296
+ /**
297
+ * Returns a new iterator.
298
+ *
299
+ * @private
300
+ * @returns {Iterator} iterator
301
+ */
302
+ function factory() {
303
+ return self.iterator( N );
304
+ }
305
+ });
306
+
307
+ /**
308
+ * Circular buffer length (i.e., capacity).
309
+ *
310
+ * @name length
311
+ * @memberof CircularBuffer.prototype
312
+ * @readonly
313
+ * @type {NonNegativeInteger}
314
+ *
315
+ * @example
316
+ * var b = new CircularBuffer( 4 );
317
+ *
318
+ * // Get the buffer capacity:
319
+ * var len = b.length;
320
+ * // returns 4
321
+ */
322
+ setReadOnlyAccessor( CircularBuffer.prototype, 'length', function get() {
323
+ return this._length;
324
+ });
325
+
326
+ /**
327
+ * Adds a value to the circular buffer.
328
+ *
329
+ * @name push
330
+ * @memberof CircularBuffer.prototype
331
+ * @type {Function}
332
+ * @param {*} value - value to add
333
+ * @returns {(*|void)} removed element or undefined
334
+ *
335
+ * @example
336
+ * var b = new CircularBuffer( 3 );
337
+ *
338
+ * // Fill the buffer:
339
+ * var v = b.push( 'foo' );
340
+ * // returns undefined
341
+ *
342
+ * v = b.push( 'bar' );
343
+ * // returns undefined
344
+ *
345
+ * v = b.push( 'beep' );
346
+ * // returns undefined
347
+ *
348
+ * // Add another value to the buffer and return the removed element:
349
+ * v = b.push( 'boop' );
350
+ * // returns 'foo'
351
+ */
352
+ setReadOnly( CircularBuffer.prototype, 'push', function push( value ) {
353
+ var set;
354
+ var get;
355
+ var buf;
356
+ var v;
357
+
358
+ buf = this._buffer.data;
359
+ get = this._buffer.accessors[ 0 ];
360
+ set = this._buffer.accessors[ 1 ];
361
+
362
+ // Compute the next buffer index:
363
+ this._i = (this._i+1) % this._length;
364
+
365
+ // Check if we are still filling the buffer...
366
+ if ( this._count < this._length ) {
367
+ set( buf, this._i, value );
368
+ this._count += 1;
369
+ return;
370
+ }
371
+ // Replace an existing buffer element...
372
+ v = get( buf, this._i );
373
+ set( buf, this._i, value );
374
+ return v;
375
+ });
376
+
377
+ /**
378
+ * Returns an array of circular buffer values.
379
+ *
380
+ * @name toArray
381
+ * @memberof CircularBuffer.prototype
382
+ * @type {Function}
383
+ * @returns {Array} circular buffer values
384
+ *
385
+ * @example
386
+ * var b = new CircularBuffer( 3 );
387
+ *
388
+ * // Add values to the buffer:
389
+ * b.push( 'foo' );
390
+ * b.push( 'bar' );
391
+ * b.push( 'beep' );
392
+ * b.push( 'boop' );
393
+ *
394
+ * // Get an array of buffer values:
395
+ * var vals = b.toArray();
396
+ * // returns [ 'bar', 'beep', 'boop' ]
397
+ */
398
+ setReadOnly( CircularBuffer.prototype, 'toArray', function toArray() {
399
+ var buf;
400
+ var get;
401
+ var out;
402
+ var k;
403
+ var i;
404
+
405
+ buf = this._buffer.data;
406
+ get = this._buffer.accessors[ 0 ];
407
+
408
+ out = [];
409
+ for ( i = 1; i <= this._count; i++ ) {
410
+ // Note: in a full buffer, `count == length`; in a partially full buffer, we need to ensure we always start at index `0`
411
+ k = (this._i+i) % this._count;
412
+ out.push( get( buf, k ) );
413
+ }
414
+ return out;
415
+ });
416
+
417
+ /**
418
+ * Serializes a circular buffer as JSON.
419
+ *
420
+ * ## Notes
421
+ *
422
+ * - `JSON.stringify()` implicitly calls this method when stringifying a `CircularBuffer` instance.
423
+ *
424
+ * @name toJSON
425
+ * @memberof CircularBuffer.prototype
426
+ * @type {Function}
427
+ * @returns {Object} serialized circular buffer
428
+ *
429
+ * @example
430
+ * var b = new CircularBuffer( 3 );
431
+ *
432
+ * // Add values to the buffer:
433
+ * b.push( 'foo' );
434
+ * b.push( 'bar' );
435
+ * b.push( 'beep' );
436
+ * b.push( 'boop' );
437
+ *
438
+ * // Serialize to JSON:
439
+ * var o = b.toJSON();
440
+ * // returns { 'type': 'circular-buffer', 'length': 3, 'data': [ 'bar', 'beep', 'boop' ] }
441
+ */
442
+ setReadOnly( CircularBuffer.prototype, 'toJSON', function toJSON() {
443
+ var out = {};
444
+ out.type = 'circular-buffer';
445
+ out.length = this._length;
446
+ out.data = this.toArray();
447
+ return out;
448
+ });
449
+
450
+
451
+ // EXPORTS //
452
+
453
+ module.exports = CircularBuffer;
package/package.json ADDED
@@ -0,0 +1,79 @@
1
+ {
2
+ "name": "@stdlib/dstructs-circular-buffer",
3
+ "version": "0.1.0",
4
+ "description": "Circular buffer.",
5
+ "license": "Apache-2.0",
6
+ "author": {
7
+ "name": "The Stdlib Authors",
8
+ "url": "https://github.com/stdlib-js/stdlib/graphs/contributors"
9
+ },
10
+ "contributors": [
11
+ {
12
+ "name": "The Stdlib Authors",
13
+ "url": "https://github.com/stdlib-js/stdlib/graphs/contributors"
14
+ }
15
+ ],
16
+ "main": "./lib",
17
+ "directories": {
18
+ "doc": "./docs",
19
+ "lib": "./lib",
20
+ "dist": "./dist"
21
+ },
22
+ "types": "./docs/types",
23
+ "scripts": {},
24
+ "homepage": "https://stdlib.io",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git://github.com/stdlib-js/dstructs-circular-buffer.git"
28
+ },
29
+ "bugs": {
30
+ "url": "https://github.com/stdlib-js/stdlib/issues"
31
+ },
32
+ "dependencies": {
33
+ "@stdlib/array-base-arraylike2object": "^0.2.1",
34
+ "@stdlib/assert-is-collection": "^0.2.2",
35
+ "@stdlib/assert-is-nonnegative-integer": "^0.2.2",
36
+ "@stdlib/assert-is-positive-integer": "^0.2.2",
37
+ "@stdlib/constants-float64-max": "^0.2.2",
38
+ "@stdlib/string-format": "^0.2.2",
39
+ "@stdlib/symbol-iterator": "^0.2.2",
40
+ "@stdlib/utils-define-nonenumerable-read-only-accessor": "^0.2.3",
41
+ "@stdlib/utils-define-nonenumerable-read-only-property": "^0.2.2",
42
+ "@stdlib/error-tools-fmtprodmsg": "^0.2.2"
43
+ },
44
+ "devDependencies": {},
45
+ "engines": {
46
+ "node": ">=0.10.0",
47
+ "npm": ">2.7.0"
48
+ },
49
+ "os": [
50
+ "aix",
51
+ "darwin",
52
+ "freebsd",
53
+ "linux",
54
+ "macos",
55
+ "openbsd",
56
+ "sunos",
57
+ "win32",
58
+ "windows"
59
+ ],
60
+ "keywords": [
61
+ "stdlib",
62
+ "data structures",
63
+ "data structure",
64
+ "data",
65
+ "structure",
66
+ "collection",
67
+ "circular",
68
+ "buffer",
69
+ "queue",
70
+ "ring",
71
+ "cyclic",
72
+ "first-in-first-out",
73
+ "fifo"
74
+ ],
75
+ "funding": {
76
+ "type": "opencollective",
77
+ "url": "https://opencollective.com/stdlib"
78
+ }
79
+ }