Last active
December 14, 2015 15:48
-
-
Save JohnB/5110195 to your computer and use it in GitHub Desktop.
Array.extract
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# We need to create Array.extract if it doesn't already exist | |
class Array | |
# Delete some of our items and return (or "extract") a new array holding the deleted items. | |
# Very similar to partition, but instead of returning copies, it modifies the original list | |
def extract | |
extracted = [] | |
# reverse our deletion so indexes don't get messed up while we're deleting | |
(length - 1).downto(0) do |idx| | |
item = self[idx] | |
extracted << delete_at(idx) if yield(item) | |
end | |
extracted.reverse | |
end | |
end | |
#require_relative "../../../lib/extensions/array_extensions.rb" | |
describe Array do | |
context "extract" do | |
it 'should modify the existing list and return a separate non-overlapping list' do | |
ar = [1,2,3,4,5] | |
odds = ar.extract { |item| item.odd? } | |
odds.should == [1,3,5] | |
ar.should == [2,4] | |
end | |
it 'should allow an empty source list' do | |
ar = [] | |
odds = ar.extract { |item| item.odd? } | |
odds.should == [] | |
ar.should == [] | |
end | |
it 'should allow an empty destination list' do | |
ar = [1,2,3,4,5] | |
none = ar.extract { |item| false } | |
none.should == [] | |
ar.should == [1,2,3,4,5] | |
end | |
it 'should allow everything to be copied' do | |
ar = [1,2,3,4,5] | |
under_ten = ar.extract { |item| item < 10 } | |
puts "ar: #{ar.inspect}." | |
puts "under_ten: #{under_ten.inspect}." | |
under_ten.should == [1,2,3,4,5] | |
ar.should == [] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment