Skip to content

Commit

Permalink
feat(utils): allow to pass custom enumerablesto .find_last
Browse files Browse the repository at this point in the history
  • Loading branch information
marian13 committed Feb 4, 2024
1 parent 5cfcefa commit 85892da
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 9 deletions.
11 changes: 8 additions & 3 deletions lib/convenient_service/utils/array/find_last.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ module Array
class FindLast < Support::Command
##
# @!attribute [r] array
# @return [Array]
# @return [Array, Enumerable]
#
attr_reader :array

Expand All @@ -17,7 +17,7 @@ class FindLast < Support::Command
attr_reader :block

##
# @param array [Array]
# @param array [Array, Enumerable]
# @param block [Proc, nil]
# @return [void]
#
Expand All @@ -29,8 +29,13 @@ def initialize(array, &block)
##
# @return [Object] Can be any type.
#
# @note Works with custom `Enumerable` objects.
# @see https://ruby-doc.org/core-2.7.0/Enumerable.html
#
def call
array.reverse.find(&block)
array.reverse_each { |item| return item if block.call(item) }

nil
end
end
end
Expand Down
34 changes: 28 additions & 6 deletions spec/lib/convenient_service/utils/array/find_last_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,48 @@
describe ".call" do
subject(:result) { described_class.call(array) { |item| item[0] == "b" } }

context "when array does NOT contain item to find" do
context "when `array` does NOT contain `item` to find" do
let(:array) { ["foo"] }

it "returns nil" do
it "returns `nil`" do
expect(result).to be_nil
end
end

context "when array contains one item to find" do
context "when `array` contains one `item` to find" do
let(:array) { ["foo", "bar"] }

it "returns that found item" do
it "returns that found `item`" do
expect(result).to eq("bar")
end
end

context "when array contains multiple items to find" do
context "when `array` contains multiple `items` to find" do
let(:array) { ["foo", "bar", "baz"] }

it "returns last from those found items" do
it "returns last from those found `items`" do
expect(result).to eq("baz")
end
end

context "when `array` is custom `Enumerable`" do
let(:klass) do
Class.new do
include Enumerable

def each(&block)
yield("foo")
yield("bar")
yield("baz")

self
end
end
end

let(:array) { klass.new }

it "does NOT use `Array` methods" do
expect(result).to eq("baz")
end
end
Expand Down

0 comments on commit 85892da

Please sign in to comment.