Skip to content

Commit

Permalink
Add Hamster::Enumerable#grep_v
Browse files Browse the repository at this point in the history
  • Loading branch information
dubek committed Dec 9, 2015
1 parent 621e649 commit ba4a801
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/hamster/enumerable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,15 @@ def grep(pattern, &block)
result
end

# Search the collection for elements which are not `#===` to `item`. Yield
# them to the optional code block if provided, and return them as a new
# collection.
def grep_v(pattern, &block)
result = select { |item| !(pattern === item) }
result = result.map(&block) if block_given?
result
end

# Yield all integers from 0 up to, but not including, the number of items in
# this collection. For collections which provide indexed access, these are all
# the valid, non-negative indices into the collection.
Expand Down
59 changes: 59 additions & 0 deletions spec/lib/hamster/set/grep_v_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
require "spec_helper"
require "hamster/set"

describe Hamster::Set do
let(:set) { S[*values] }

describe "#grep_v" do
let(:grep_v) { set.grep_v(String, &block) }

shared_examples "check filtered values" do
it "returns the filtered values" do
expect(grep_v).to eq(S[*filtered])
end
end

context "without a block" do
let(:block) { nil }

context "with an empty set" do
let(:values) { [] }
let(:filtered) { [] }

include_examples "check filtered values"
end

context "with a single item set" do
let(:values) { ["A"] }
let(:filtered) { [] }

include_examples "check filtered values"
end

context "with a single item set that doesn't contain match" do
let(:values) { [1] }
let(:filtered) { [1] }

include_examples "check filtered values"
end

context "with a multi-item set where one isn't a match" do
let(:values) { [2, "C", 4] }
let(:filtered) { [2, 4] }

include_examples "check filtered values"
end
end

describe "with a block" do
let(:block) { ->(item) { item + 100 }}

context "resulting items are processed with the block" do
let(:values) { [2, "C", 4] }
let(:filtered) { [102, 104] }

include_examples "check filtered values"
end
end
end
end

0 comments on commit ba4a801

Please sign in to comment.