Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. export class Queue<T> {
  2. /**
  3. * The elements in the queue
  4. */
  5. private elements: T[] = []
  6. /**
  7. * The head (index) of the queue.
  8. * For performance, this is not always zero, as would be expected.
  9. */
  10. private head = 0
  11. /**
  12. *
  13. */
  14. get length(): number {
  15. return this.elements.length - this.head
  16. };
  17. empty(): boolean {
  18. return this.elements.length === 0
  19. };
  20. put(element: T): void {
  21. this.elements.push(element)
  22. };
  23. get(): T {
  24. if (0 !== this.elements.length) {
  25. const c = this.elements[this.head]
  26. this.head++
  27. // If over half of the elements towards the front of the queue are no longer needed,
  28. // re-allocated the elements.
  29. if (2 * this.head >= this.elements.length) {
  30. this.elements = this.elements.slice(this.head)
  31. this.head = 0
  32. }
  33. return c
  34. }
  35. else {
  36. throw new Error("")
  37. }
  38. }
  39. peek(): T | undefined {
  40. return this.elements.length > 0 ? this.elements[this.head] : void 0
  41. }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement