CircularBuffer.js.flow 886 B

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