Skip to content

Commit ec56944

Browse files
author
Pedro David Rodríguez Sánchez
committed
Backwards iterator implemented and tested
1 parent 0abd7ac commit ec56944

4 files changed

Lines changed: 47 additions & 5 deletions

File tree

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,20 @@
11
package oop.Iterator
22

3-
class BackwardsIterator {
3+
class BackwardsIterator<T>(list: MutableList<T>): NormalIterator<T>(list) {
4+
override fun first(): T? {
5+
index = list.size - 1
6+
return get()
7+
}
48

9+
override fun hasNext(): Boolean = index - 1 > -1
10+
11+
override fun hasPrev(): Boolean = this.list.size > index + 1
12+
13+
override fun nextIndex(): Int = if(index > -1) index - 1 else -1
14+
15+
override fun prevIndex(): Int = if(index > this.list.size) index +1 else -1
16+
17+
override fun next(): T? = if (hasNext()) list[index--] else throw NoSuchElementException()
18+
19+
override fun prev(): T? = if (hasPrev()) list[index++] else throw NoSuchElementException()
520
}

src/main/kotlin/oop/Iterator/NormalIterator.kt

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package oop.Iterator
22

3-
class NormalIterator<T>(val list: MutableList<T>) : Iterator<T> {
4-
private var index = 0
3+
open class NormalIterator<T>(val list: MutableList<T>) : Iterator<T> {
4+
protected var index = 0
55

66
override fun first(): T? {
77
index = 0
@@ -18,7 +18,7 @@ class NormalIterator<T>(val list: MutableList<T>) : Iterator<T> {
1818

1919
override fun next(): T? = if (hasNext()) list[index++] else throw NoSuchElementException()
2020

21-
override fun prev(): T? = if (hasPrev()) list[index++] else throw NoSuchElementException()
21+
override fun prev(): T? = if (hasPrev()) list[index--] else throw NoSuchElementException()
2222

2323
override fun set(element: T) {
2424
list[index] = element
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
package oop.Iterator
22

3-
class RandomIterator {
3+
class RandomIterator<T>(list: MutableList<T>): NormalIterator<T>(list) {
4+
45
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package oop.Iterator
2+
3+
4+
import org.hamcrest.CoreMatchers.`is`
5+
import org.hamcrest.MatcherAssert.assertThat
6+
import org.junit.Test
7+
8+
class BackwardsIteratorShould {
9+
private val list = mutableListOf("10", "12", "15", "29", "30", "36")
10+
private val iterator: Iterator<String> = BackwardsIterator(list)
11+
12+
@Test
13+
fun `Return last item of collection when call`(){
14+
assertThat(iterator.first(),`is`("36"))
15+
}
16+
17+
@Test
18+
fun `Iterate list from back to start`(){
19+
var res = ""
20+
iterator.first()
21+
iterator.forEach {
22+
res += "$it,"
23+
}
24+
assertThat(res, `is`("36,30,29,15,12,10,"))
25+
}
26+
}

0 commit comments

Comments
 (0)