Skip to content

Commit

Permalink
Slice improvements (WIP)
Browse files Browse the repository at this point in the history
  • Loading branch information
skozlov committed Aug 5, 2024
1 parent ca0cbba commit 4054550
Showing 1 changed file with 55 additions and 1 deletion.
56 changes: 55 additions & 1 deletion src/main/scala/com/github/skozlov/commons/collection/Slice.scala
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ trait SliceOps[
] extends IndexedSeqView[A] {
this: SubSlice =>

import SliceOps._
import SliceOps.*

def underlying: Underlying
def from: Int
Expand Down Expand Up @@ -59,6 +59,60 @@ trait SliceOps[
override def takeRight(n: Int): SubSlice = drop(length - math.max(n, 0))

override def dropRight(n: Int): SubSlice = take(length - math.max(n, 0))

override def tail: SubSlice = {
if (isEmpty) {
throw new UnsupportedOperationException("Empty Slice doesn't have .tail")
}
drop(1)
}

override def init: SubSlice = {
if (isEmpty) {
throw new UnsupportedOperationException("Empty Slice doesn't have .init")
}
dropRight(1)
}

override def tails: Iterator[SubSlice] = {
for (numDrop <- Iterator.range(0, length + 1)) yield drop(numDrop)
}

override def inits: Iterator[SubSlice] = {
for (numDrop <- Iterator.range(0, length + 1)) yield dropRight(numDrop)
}

override def sliding(size: Int, step: Int): Iterator[SubSlice] = {
require(size >= 1, s"Too small size: $size")
require(step >= 1, s"Too small step: $step")
Iterator
.iterate(0 until size) { range =>
(range.start + step) until (range.end + step)
}
.takeWhile { _.start < length }
.map { range =>
this.slice(
from = range.start,
until = math.min(range.end, length),
)
}
}

override def sliding(size: Int): Iterator[SubSlice] = {
sliding(size, step = 1)
}

override def grouped(size: Int): Iterator[SubSlice] = {
sliding(size, step = size)
}

override def copyToArray[B >: A](xs: Array[B], start: Int, len: Int): Int = {
underlying.copyToArray(
xs,
indexToUnderlying(start),
math.min(len, length - start),
)
}
}

object SliceOps {
Expand Down

0 comments on commit 4054550

Please sign in to comment.