Skip to content

Commit e1672e4

Browse files
committed
Add non-sequence version of EveryOther and EveryNth
1 parent 5b4c2d0 commit e1672e4

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/main/kotlin/org/athenian/EveryNthSequence.kt

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package org.athenian
22

3+
import java.util.concurrent.atomic.AtomicInteger
4+
35
fun <T> Sequence<T>.everyNth(inc: Int) = EveryNthSequence(inc, this)
46

57
class EveryNthSequence<T>(private val inc: Int, private val underlyingSequence: Sequence<T>) : Sequence<T> {
@@ -20,10 +22,24 @@ class EveryNthSequence<T>(private val inc: Int, private val underlyingSequence:
2022
}
2123
}
2224

25+
public fun <T> Iterable<T>.everyNth(inc: Int): List<T> = everyNth(ArrayList<T>(), inc)
26+
27+
public fun <T, C : MutableCollection<in T>> Iterable<T>.everyNth(destination: C, inc: Int): C {
28+
val counter = AtomicInteger(0)
29+
for (element in this)
30+
if (counter.getAndIncrement() % inc == 0)
31+
destination.add(element)
32+
return destination
33+
}
34+
35+
2336
fun main() {
2437
(0..50)
2538
.asSequence()
2639
.everyNth(5)
2740
.forEach { println("Value: $it") }
2841

42+
(0..50)
43+
.everyNth(5)
44+
.forEach { println("Value: $it") }
2945
}

src/main/kotlin/org/athenian/EveryOtherSequence.kt

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package org.athenian
22

3+
import java.util.concurrent.atomic.AtomicInteger
4+
35
fun <T> Sequence<T>.everyOther() = EveryOtherSequence(this)
46

57
class EveryOtherSequence<T>(private val underlyingSequence: Sequence<T>) : Sequence<T> {
@@ -18,9 +20,23 @@ class EveryOtherSequence<T>(private val underlyingSequence: Sequence<T>) : Seque
1820
}
1921
}
2022

23+
public fun <T> Iterable<T>.everyOther(): List<T> = everyOther(ArrayList<T>())
24+
25+
public fun <T, C : MutableCollection<in T>> Iterable<T>.everyOther(destination: C): C {
26+
val counter = AtomicInteger(0)
27+
for (element in this)
28+
if (counter.getAndIncrement() % 2 == 0)
29+
destination.add(element)
30+
return destination
31+
}
32+
2133
fun main() {
2234
(0..10)
2335
.asSequence()
2436
.everyOther()
2537
.forEach { println("Value: $it") }
38+
39+
(0..10)
40+
.everyOther()
41+
.forEach { println("Value: $it") }
2642
}

0 commit comments

Comments
 (0)