diff --git a/lib/foobara/util/array.rb b/lib/foobara/util/array.rb index 6fae26d..318e4d3 100644 --- a/lib/foobara/util/array.rb +++ b/lib/foobara/util/array.rb @@ -36,5 +36,15 @@ def all_blank_or_false?(array) ) end end + + def start_with?(large_array, small_array) + return false unless large_array.size >= small_array.size + + small_array.each.with_index do |item, index| + return false unless large_array[index] == item + end + + true + end end end diff --git a/spec/array_spec.rb b/spec/array_spec.rb index 666408a..a8469a5 100644 --- a/spec/array_spec.rb +++ b/spec/array_spec.rb @@ -36,4 +36,50 @@ it { is_expected.to be(true) } end end + + describe ".start_with?" do + subject { described_class.start_with?(large_array, small_array) } + + context "when size of large array is smaller than size of small array" do + let(:large_array) { [1, 2, 3] } + let(:small_array) { [1, 2, 3, 4, 5, 6, 7] } + + it { is_expected.to be(false) } + end + + context "when large array starts with elements from small array" do + let(:large_array) { [1, 2, 3, 4, 5, 6, 7] } + let(:small_array) { [1, 2, 3, 4] } + + it { is_expected.to be(true) } + end + + context "when elements in small array don't match those in large array" do + let(:large_array) { [1, 2, 3, 4, 5, 6, 7] } + let(:small_array) { [5, 6, 7, 8] } + + it { is_expected.to be(false) } + end + + context "when first elements in small array match those in the large array but last elements don't match" do + let(:large_array) { [1, 2, 3, 4, 5, 6, 7] } + let(:small_array) { [1, 2, 8, 9] } + + it { is_expected.to be(false) } + end + + context "when small array and large array are of the same size" do + let(:large_array) { [1, 2, 3, 4] } + let(:small_array) { [1, 2, 3, 4] } + + it { is_expected.to be(true) } + end + + context "when both arrays are empty" do + let(:large_array) { [] } + let(:small_array) { [] } + + it { is_expected.to be(true) } + end + end end