|
RSpec.describe Patches::Proc::Composition do |
|
let(:reverse) { proc {|x| x.reverse } } |
|
let(:uppercase) { proc {|x| x.upcase } } |
|
let(:ascii_nums) { proc {|x| x.split('').map(&:ord) } } |
|
|
|
describe "<<" do |
|
it "allows procs to be stuck together in a pipeline" do |
|
expect((ascii_nums << uppercase << reverse).call("Hello World")).to eq [68, 76, 82, 79, 87, 32, 79, 76, 76, 69, 72] |
|
end |
|
|
|
it "doesn't matter which bits of the pipeline you stick together first" do # (is associative) |
|
expect( |
|
((ascii_nums << uppercase) << reverse).call("Hello World") |
|
).to eq( |
|
(ascii_nums << (uppercase << reverse)).call("Hello World") |
|
) |
|
end |
|
|
|
it "matters what order the bits of the pipeline are stuck together" do # (is not commutative) |
|
expect((ascii_nums << uppercase << reverse).call("Hello World")).to eq [68, 76, 82, 79, 87, 32, 79, 76, 76, 69, 72] |
|
expect{(uppercase << ascii_nums << reverse).call("Hello World")}.to raise_error |
|
expect{(uppercase << reverse << ascii_nums).call("Hello World")}.to raise_error |
|
end |
|
|
|
it "duck-types on #to_proc when composing" do |
|
# More of an accident than anything. Symbol has to_proc(), which converts ":to_s" to "proc {|x| x.to_s }". |
|
expect((reverse << :to_s).call(123)).to eq "321" |
|
end |
|
end |
|
|
|
describe ">>" do |
|
it "allows procs to be stuck together in a pipeline" do |
|
expect((uppercase >> reverse >> ascii_nums).call("Hello World")).to eq [68, 76, 82, 79, 87, 32, 79, 76, 76, 69, 72] |
|
end |
|
|
|
it "doesn't matter which bits of the pipeline you stick together first" do # (is associative) |
|
expect( |
|
((uppercase >> reverse) >> ascii_nums).call("Hello World") |
|
).to eq( |
|
(uppercase >> (reverse >> ascii_nums)).call("Hello World") |
|
) |
|
end |
|
|
|
it "matters what order the bits of the pipeline are stuck together" do # (is not commutative) |
|
expect((uppercase >> reverse >> ascii_nums).call("Hello World")).to eq [68, 76, 82, 79, 87, 32, 79, 76, 76, 69, 72] |
|
expect{(uppercase >> ascii_nums >> reverse).call("Hello World")}.to raise_error |
|
expect{(ascii_nums >> uppercase >> reverse).call("Hello World")}.to raise_error |
|
end |
|
|
|
it "duck-types on #to_proc when composing" do |
|
# More of an accident than anything. Symbol has to_proc(), which converts ":to_i" to "proc {|x| x.to_i }". |
|
expect((reverse >> :to_i).call("123")).to eq 321 |
|
end |
|
end |
|
end |