index.js 972 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. const FixedFIFO = require('./fixed-size')
  2. module.exports = class FastFIFO {
  3. constructor (hwm) {
  4. this.hwm = hwm || 16
  5. this.head = new FixedFIFO(this.hwm)
  6. this.tail = this.head
  7. this.length = 0
  8. }
  9. clear () {
  10. this.head = this.tail
  11. this.head.clear()
  12. this.length = 0
  13. }
  14. push (val) {
  15. this.length++
  16. if (!this.head.push(val)) {
  17. const prev = this.head
  18. this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)
  19. this.head.push(val)
  20. }
  21. }
  22. shift () {
  23. if (this.length !== 0) this.length--
  24. const val = this.tail.shift()
  25. if (val === undefined && this.tail.next) {
  26. const next = this.tail.next
  27. this.tail.next = null
  28. this.tail = next
  29. return this.tail.shift()
  30. }
  31. return val
  32. }
  33. peek () {
  34. const val = this.tail.peek()
  35. if (val === undefined && this.tail.next) return this.tail.next.peek()
  36. return val
  37. }
  38. isEmpty () {
  39. return this.length === 0
  40. }
  41. }