Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions core/src/main/scala/ox/flow/FlowCompanionOps.scala
Original file line number Diff line number Diff line change
Expand Up @@ -85,13 +85,18 @@ trait FlowCompanionOps:
emit(t)
t = f(t)

/** Creates a flow which emits a range of numbers, from `from`, to `to` (inclusive), stepped by `step`. */
def range(from: Int, to: Int, step: Int): Flow[Int] = usingEmitInline: emit =>
var t = from
repeatWhile:
emit(t)
t = t + step
t <= to
/** Creates a flow which emits a range of numbers, from `from`, to `to` (inclusive), stepped by `step`. A negative `step` produces a
* descending range, e.g. `range(5, 1, -1)` emits `5, 4, 3, 2, 1`. The `step` must be non-zero.
*/
def range(from: Int, to: Int, step: Int): Flow[Int] =
require(step != 0, "step must be non-zero")
usingEmitInline: emit =>
var t = from
repeatWhile:
emit(t)
t = t + step
if step >= 0 then t <= to else t >= to
end range

/** Creates a flow which emits the first element of tuples returned by repeated applications of `f`. The `initial` state is used for the
* first application, and then the state is updated with the second element of the tuple. Emission stops when `f` returns `None`,
Expand Down
4 changes: 4 additions & 0 deletions core/src/test/scala/ox/flow/FlowOpsFactoryMethodsTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,8 @@ class FlowOpsFactoryMethodsTest extends AnyFlatSpec with Matchers:
Flow.range(1, 5, 1).runToList() shouldBe List(1, 2, 3, 4, 5)
Flow.range(1, 5, 2).runToList() shouldBe List(1, 3, 5)
Flow.range(1, 11, 3).runToList() shouldBe List(1, 4, 7, 10)

it should "produce a descending range with a negative step" in:
Flow.range(5, 1, -1).runToList() shouldBe List(5, 4, 3, 2, 1)
Flow.range(10, 0, -2).runToList() shouldBe List(10, 8, 6, 4, 2, 0)
end FlowOpsFactoryMethodsTest
Loading