Skip to content

Commit

Permalink
add EntityBagIterator.kt
Browse files Browse the repository at this point in the history
  • Loading branch information
Quillraven committed Dec 23, 2024
1 parent c694660 commit c765d1f
Show file tree
Hide file tree
Showing 4 changed files with 1,022 additions and 878 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package com.github.quillraven.fleks.collection

import com.github.quillraven.fleks.Entity

/**
* Creates an [EntityBagIterator] for the bag. If the bag gets updated
* during iteration then [EntityBagIterator.reset] must be called to guarantee correct iterator behavior.
*/
fun EntityBag.iterator(): EntityBagIterator = EntityBagIterator(this)

/**
* An iterator over an [EntityBag]. Allows to iterate in forward and backward direction.
* Also, supports looping iteration which means that if the iterator is at the end/beginning of
* the bag, then it will go to the beginning/end of the bag.
* The iterator returns [Entity.NONE] in case an [entity][Entity] does not exist.
*/
data class EntityBagIterator(private val bag: EntityBag) {
private var currentIdx = 0

/**
* Returns **true** if and only if there is a next [entity][Entity] in the bag.
*/
fun hasNext(): Boolean = currentIdx < bag.size

/**
* Returns the next [entity][Entity] of the bag and moves the iterator forward.
* If [loop] is true then the iterator starts again from the beginning if it is at the end.
*/
fun next(loop: Boolean = false): Entity = when {
hasNext() -> bag[currentIdx++]

loop && bag.isNotEmpty() -> {
currentIdx = 0
bag[currentIdx]
}

else -> Entity.NONE
}

/**
* Returns **true** if and only if there is a previous [entity][Entity] in the bag.
*/
fun hasPrevious(): Boolean = currentIdx > 0

/**
* Returns the previous [entity][Entity] of the bag and moves the iterator backward.
* If [loop] is true then the iterator starts again at the end if it is at the beginning.
*/
fun previous(loop: Boolean = false): Entity = when {
hasPrevious() -> bag[--currentIdx]

loop && bag.isNotEmpty() -> {
currentIdx = bag.size - 1
bag[currentIdx]
}

else -> Entity.NONE
}

/**
* Resets the iterator to the beginning of the bag.
*/
fun reset() {
currentIdx = 0
}
}
Loading

0 comments on commit c765d1f

Please sign in to comment.