Skip to content

Commit

Permalink
Add Iterator(T).empty (#15039)
Browse files Browse the repository at this point in the history
  • Loading branch information
spuun authored Oct 10, 2024
1 parent 0606cf0 commit f237af0
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
7 changes: 7 additions & 0 deletions spec/std/iterator_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ private class MockIterator
end

describe Iterator do
describe "Iterator.empty" do
it "creates empty iterator" do
iter = Iterator(String).empty
iter.next.should be_a(Iterator::Stop)
end
end

describe "Iterator.of" do
it "creates singleton" do
iter = Iterator.of(42)
Expand Down
13 changes: 13 additions & 0 deletions src/iterator.cr
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,19 @@ module Iterator(T)
Stop::INSTANCE
end

# Returns an empty iterator.
def self.empty
EmptyIterator(T).new
end

private struct EmptyIterator(T)
include Iterator(T)

def next
stop
end
end

def self.of(element : T)
SingletonIterator(T).new(element)
end
Expand Down

0 comments on commit f237af0

Please sign in to comment.