Module: Tafel
- Defined in:
- lib/tafel.rb
Constant Summary collapse
- VERSION =
'1.0.0'
Class Method Summary collapse
- .flatten(table) ⇒ Object
- .table?(o) ⇒ Boolean
- .to_htable(x) ⇒ Object (also: to_h)
-
.to_vtable(x, limit = -1)) ⇒ Object
(also: to_v)
.to_vtable: keys are arrayed vertically (y explosion) .to_htable: keys are arrayed horizontally (x explosion).
Class Method Details
.flatten(table) ⇒ Object
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
# File 'lib/tafel.rb', line 74 def self.flatten(table) fail ArgumentError.new('not a table') unless table?(table) flat = true table = table.collect { |r| r.collect { |c| next c unless table?(c); flat = false; flatten(c) } } return table if flat ss = table.collect { |r| r.collect { |c| size(c) } } ss.each do |row| maxh = row.collect { |cell| cell[1] }.max maxh = maxh < 1 ? 1 : maxh row.each { |cell| cell[1] = maxh } end ss.collect { |row| row.size }.max.times do |x| maxw = ss.collect { |row| cell = row[x]; cell ? cell[0] : 1 }.max maxw = maxw < 1 ? 1 : maxw ss.each { |row| cell = row[x]; cell[0] = maxw if cell } end w = ss.first.collect(&:first).reduce(&:+) h = ss.collect { |row| row[0].last }.reduce(&:+) a = Array.new(h) { Array.new(w) } iterate(ss) do |x, y, s| left = x > 0 ? ss[y][x - 1] : nil above = y > 0 ? ss[y - 1][x] : nil woff = left ? left[2] + left[0] : 0 hoff = above ? above[3] + above[1] : 0 s.push(woff, hoff) copy(a, woff, hoff, table[y][x]) end a end |
.table?(o) ⇒ Boolean
30 31 32 33 |
# File 'lib/tafel.rb', line 30 def self.table?(o) o.is_a?(Array) && o.all? { |r| r.is_a?(Array) } end |
.to_htable(x) ⇒ Object Also known as: to_h
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/tafel.rb', line 49 def self.to_htable(x) kla0 = narrow_class(x) kla1 = nil if kla0 vs = x.respond_to?(:values) ? x.values : x kla = narrow_class(vs.first) kla1 = vs.all? { |v| kla ? v.is_a?(kla) : false } ? kla : nil end #p [ kla0, kla1 ] case [ kla0, kla1 ] when [ Hash, Hash ] then to_h_hash_hash(x) when [ Array, Hash ] then to_h_array_hash(x) when [ Hash, nil ] then to_h_hash(x) else x end end |
.to_vtable(x, limit = -1)) ⇒ Object Also known as: to_v
.to_vtable: keys are arrayed vertically (y explosion) .to_htable: keys are arrayed horizontally (x explosion)
38 39 40 41 42 43 44 45 46 47 |
# File 'lib/tafel.rb', line 38 def self.to_vtable(x, limit=-1) return x if limit == 0 case x when Hash then x.to_a.collect { |k, v| [ k, to_vtable(v, limit - 1) ] } when Array then x.inject([]) { |a, e| a << [ a.size, to_vtable(e) ]; a } else x end end |