|
| 1 | +package com.github.quillraven.fleks.collection |
| 2 | + |
| 3 | +import com.github.quillraven.fleks.Entity |
| 4 | + |
| 5 | +/** |
| 6 | + * Creates an [EntityBagIterator] for the bag. If the bag gets updated |
| 7 | + * during iteration then [EntityBagIterator.reset] must be called to guarantee correct iterator behavior. |
| 8 | + */ |
| 9 | +fun EntityBag.iterator(): EntityBagIterator = EntityBagIterator(this) |
| 10 | + |
| 11 | +/** |
| 12 | + * An iterator over an [EntityBag]. Allows to iterate in forward and backward direction. |
| 13 | + * Also, supports looping iteration which means that if the iterator is at the end/beginning of |
| 14 | + * the bag, then it will go to the beginning/end of the bag. |
| 15 | + * The iterator returns [Entity.NONE] in case an [entity][Entity] does not exist. |
| 16 | + */ |
| 17 | +data class EntityBagIterator(private val bag: EntityBag) { |
| 18 | + private var currentIdx = 0 |
| 19 | + |
| 20 | + /** |
| 21 | + * Returns **true** if and only if there is a next [entity][Entity] in the bag. |
| 22 | + */ |
| 23 | + fun hasNext(): Boolean = currentIdx < bag.size |
| 24 | + |
| 25 | + /** |
| 26 | + * Returns the next [entity][Entity] of the bag and moves the iterator forward. |
| 27 | + * If [loop] is true then the iterator starts again from the beginning if it is at the end. |
| 28 | + */ |
| 29 | + fun next(loop: Boolean = false): Entity = when { |
| 30 | + hasNext() -> bag[currentIdx++] |
| 31 | + |
| 32 | + loop && bag.isNotEmpty() -> { |
| 33 | + currentIdx = 0 |
| 34 | + bag[currentIdx] |
| 35 | + } |
| 36 | + |
| 37 | + else -> Entity.NONE |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Returns **true** if and only if there is a previous [entity][Entity] in the bag. |
| 42 | + */ |
| 43 | + fun hasPrevious(): Boolean = currentIdx > 0 |
| 44 | + |
| 45 | + /** |
| 46 | + * Returns the previous [entity][Entity] of the bag and moves the iterator backward. |
| 47 | + * If [loop] is true then the iterator starts again at the end if it is at the beginning. |
| 48 | + */ |
| 49 | + fun previous(loop: Boolean = false): Entity = when { |
| 50 | + hasPrevious() -> bag[--currentIdx] |
| 51 | + |
| 52 | + loop && bag.isNotEmpty() -> { |
| 53 | + currentIdx = bag.size - 1 |
| 54 | + bag[currentIdx] |
| 55 | + } |
| 56 | + |
| 57 | + else -> Entity.NONE |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * Resets the iterator to the beginning of the bag. |
| 62 | + */ |
| 63 | + fun reset() { |
| 64 | + currentIdx = 0 |
| 65 | + } |
| 66 | +} |
0 commit comments