fixed-size.js 776 B

123456789101112131415161718192021222324252627282930313233
  1. module.exports = class FixedFIFO {
  2. constructor (hwm) {
  3. if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
  4. this.buffer = new Array(hwm)
  5. this.mask = hwm - 1
  6. this.top = 0
  7. this.btm = 0
  8. this.next = null
  9. }
  10. push (data) {
  11. if (this.buffer[this.top] !== undefined) return false
  12. this.buffer[this.top] = data
  13. this.top = (this.top + 1) & this.mask
  14. return true
  15. }
  16. shift () {
  17. const last = this.buffer[this.btm]
  18. if (last === undefined) return undefined
  19. this.buffer[this.btm] = undefined
  20. this.btm = (this.btm + 1) & this.mask
  21. return last
  22. }
  23. peek () {
  24. return this.buffer[this.btm]
  25. }
  26. isEmpty () {
  27. return this.buffer[this.btm] === undefined
  28. }
  29. }