CircularBuffer.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. /**
  3. * Copyright (c) 2013-present, Facebook, Inc.
  4. *
  5. * This source code is licensed under the MIT license found in the
  6. * LICENSE file in the root directory of this source tree.
  7. *
  8. */
  9. var invariant = require("./invariant");
  10. var CircularBuffer =
  11. /*#__PURE__*/
  12. function () {
  13. function CircularBuffer(size) {
  14. !(size > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'Buffer size should be a positive integer') : invariant(false) : void 0;
  15. this._size = size;
  16. this._head = 0;
  17. this._buffer = [];
  18. }
  19. var _proto = CircularBuffer.prototype;
  20. _proto.write = function write(entry) {
  21. if (this._buffer.length < this._size) {
  22. this._buffer.push(entry);
  23. } else {
  24. this._buffer[this._head] = entry;
  25. this._head++;
  26. this._head %= this._size;
  27. }
  28. return this;
  29. };
  30. _proto.read = function read() {
  31. return this._buffer.slice(this._head).concat(this._buffer.slice(0, this._head));
  32. };
  33. _proto.clear = function clear() {
  34. this._head = 0;
  35. this._buffer = [];
  36. return this;
  37. };
  38. return CircularBuffer;
  39. }();
  40. module.exports = CircularBuffer;