# Chapter 13 (Iterator) - Queue Implementation

**URL:** <https://forums.kodeco.com/t/chapter-13-iterator-queue-implementation/120493>\
**Category:** Design Patterns by Tutorials\
**Created:** [September 20, 2020, 5:59pm UTC](https://forums.kodeco.com/t/chapter-13-iterator-queue-implementation/120493 "2020-09-20T17:59:20Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![leopic](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/leopic/32/96569_2.png) [@leopic](https://forums.kodeco.com/u/leopic)\
**Post date:** [September 20, 2020, 5:59pm UTC](https://forums.kodeco.com/t/chapter-13-iterator-queue-implementation/120493/1 "2020-09-20T17:59:20Z")

</div>

In the implementation for the `dequeue` method, there is a check made for the total elements in the array and the `percentage`? What is this used for?

```swift
public mutating func dequeue() -> T? {
    guard head < array.count,
          let element = array[head] else {
      return nil
    }

    array[head] = nil
    head += 1

    let percentage = Double(head)/Double(array.count) // What is this doing?
    if array.count > 50, // What's different between having 40 or 60 elements?
       percentage > 0.25 { // Is this necessary? We already have an element
      array.removeFirst()
      head = 0
    }

    return element
  }

```

---

<div class="post-metadata">

**Author:** ![mokhet](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/mokhet/32/102075_2.png) [@mokhet](https://forums.kodeco.com/u/mokhet)\
**Post date:** [September 21, 2020, 9:51am UTC](https://forums.kodeco.com/t/chapter-13-iterator-queue-implementation/120493/2 "2020-09-21T09:51:01Z")

</div>

Everything is explained in the [GitHub repository swift-algorithm-club/Queue](https://github.com/raywenderlich/swift-algorithm-club/tree/master/Queue)

> If we never remove those empty spots at the front then the array will keep growing as we enqueue and dequeue elements. To periodically trim down the array, we do the following:

```let
    if array.count > 50 && percentage > 0.25 {
      array.removeFirst(head)
      head = 0
    }

```

> This calculates the percentage of empty spots at the beginning as a ratio of the total array size. If more than 25% of the array is unused, we chop off that wasted space. However, if the array is small we do not resize it all the time, so there must be at least 50 elements in the array before we try to trim it.

---

<div class="post-metadata">

**Author:** ![leopic](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/leopic/32/96569_2.png) [@leopic](https://forums.kodeco.com/u/leopic)\
**Post date:** [September 21, 2020, 1:38pm UTC](https://forums.kodeco.com/t/chapter-13-iterator-queue-implementation/120493/3 "2020-09-21T13:38:51Z")

</div>

Thank you so much @mokhet, that makes more sense now, seems to be related to memory optimizations but unrelated to the task at hand.
