Skip to content

Commit

Permalink
add all? to SortedArray
Browse files Browse the repository at this point in the history
  • Loading branch information
GarrisonJ committed Apr 29, 2024
1 parent c138041 commit 0ff0a2f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/sorted_containers/sorted_array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,21 @@ def abbrev(pattern = nil)
to_a.abbrev(pattern)
end

# Returns true if all elements of self meet the given criterion.
# If the block is not given, returns true if all elements are truthy.
# If self is empty, returns true.
#
# @yield [value] The block to check with.
# @return [Boolean] True if all elements meet the given criterion, false otherwise.
def all?
if block_given?
each { |value| return false unless yield(value) }
else
each { |value| return false unless value }
end
true
end

# Returns a string representation of the sorted array.
#
# @return [String] A string representation of the sorted array.
Expand Down
27 changes: 27 additions & 0 deletions spec/sorted_array_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,33 @@
end
end

describe "all?" do
it "should return true if all elements meet a given criterion" do
array = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
expect(array.all? { |i| i > 0 }).to be true
end

it "should return false if all elements do not meet a given criterion" do
array = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
expect(array.all? { |i| i > 1 }).to be false
end

it "should return true if the array contains only truthy elements" do
array = SortedContainers::SortedArray.new([1, 2, 3, 4, 5])
expect(array.all?).to be true
end

it "should return false if the array contains a falsy element" do
array = SortedContainers::SortedArray.new([false, false])
expect(array.all?).to be false
end

it "should return true if the array is empty" do
array = SortedContainers::SortedArray.new
expect(array.all?).to be true
end
end

describe "load_factor" do
it "should set the load factor to the provided value" do
array = SortedContainers::SortedArray.new([], load_factor: 100)
Expand Down

0 comments on commit 0ff0a2f

Please sign in to comment.