From 4118c4f596092b0c7b0ee2e9bab3e6989b741dd5 Mon Sep 17 00:00:00 2001 From: Mike Pastore Date: Thu, 15 Sep 2016 20:46:01 -0500 Subject: [PATCH] Miscellaneous work and finagling * Prefer lambda-first over block in conflict resolution * Limit the amount of flattening done to allow esoteric hash key types * Fore! --- lib/ioughta.rb | 30 +++++++----------------------- spec/ioughta_spec.rb | 24 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 23 deletions(-) diff --git a/lib/ioughta.rb b/lib/ioughta.rb index 0ba9096..87b06b2 100644 --- a/lib/ioughta.rb +++ b/lib/ioughta.rb @@ -24,35 +24,19 @@ def ioughta_hash(*data, &block) SKIP_SYMBOL = :_ def pair(data, &block) - data = data.flatten - lam = - if block - block - elsif data.first.respond_to?(:call) - data.shift - else - DEFAULT_LAMBDA - end - - (0..Float::INFINITY).lazy.each do |i| - if i % 2 != 0 - if data[i].respond_to?(:call) - lam = data[i] - else - data.insert(i, lam) - end - elsif data[i].nil? - break - end + data = data.flatten(1) + lam = (data.shift if data[0].respond_to?(:call)) || block || DEFAULT_LAMBDA + + data.map.with_index do |c, i, j = i.succ| + [c, data[j].respond_to?(:call) ? lam = data.slice!(j) : lam] end - data end def each_resolved_pair(data) return enum_for(__method__, data) { data.length / 2 } unless block_given? - data.each_slice(2).with_index do |(nom, lam), iota| - val = lam.call(*[iota, nom].take(lam.arity.abs)) + data.each_with_index do |(nom, lam), iota| + val = lam[*[iota, nom].take(lam.arity.abs)] next if nom == SKIP_SYMBOL yield nom, val end diff --git a/spec/ioughta_spec.rb b/spec/ioughta_spec.rb index f0253ae..27f3e1e 100644 --- a/spec/ioughta_spec.rb +++ b/spec/ioughta_spec.rb @@ -124,4 +124,28 @@ module Foo expect(Foo::BYTES[:GB]).to eq(2 ** 30) end end + + describe 'esoteric keys' do + before do + module Foo + include Ioughta + + FOO = ioughta_hash([ + [:a, :b], + {:c=>1, :d=>2}, + nil + ]).freeze + end + end + + after do + Object.send(:remove_const, :Foo) + end + + it "accepts weird key classes" do + expect(Foo::FOO.keys[0]).to be_a(Array) + expect(Foo::FOO.keys[1]).to be_a(Hash) + expect(Foo::FOO.keys[2]).to be_a(NilClass) + end + end end