Skip to content

Commit

Permalink
fix: formatters return array to support slices
Browse files Browse the repository at this point in the history
  • Loading branch information
jozefvaclavik committed Jun 17, 2024
1 parent 84bed2d commit 60219b0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
17 changes: 12 additions & 5 deletions lib/trifle/stats/formatter/category.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,19 @@ class Formatter
class Category
Trifle::Stats::Series.register_formatter(:category, self)

def format(series:, path:)
def format(series:, path:, slices: 1, &block)
keys = path.split('.')
series[:at].each_with_object(Hash.new(0)).with_index do |(_at, map), i|
series[:values][i].dig(*keys).each do |key, value|
k, v = block_given? ? yield(key, value) : [key.to_s, value.to_f]
map[k] += v
result = series[:at].zip(series[:values].map { |v| v.dig(*keys) || {} })
sliced(result: result, slices: slices, block: block)
end

def sliced(result:, slices:, block: nil) # rubocop:disable Metrics/AbcSize
result[(result.count - (result.count / slices * slices))..].each_slice(result.count / slices).map do |slice|
slice.each_with_object(Hash.new(0)) do |(_at, data), map|
data.each do |key, value|
k, v = block ? block.call(key, value) : [key.to_s, value.to_f]
map[k] += v
end
end
end
end
Expand Down
14 changes: 10 additions & 4 deletions lib/trifle/stats/formatter/timeline.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,17 @@ class Formatter
class Timeline
Trifle::Stats::Series.register_formatter(:timeline, self)

def format(series:, path:)
def format(series:, path:, slices: 1, &block)
keys = path.split('.')
series[:at].map.with_index do |at, i|
value = series[:values][i].dig(*keys)
block_given? ? yield(at, value) : [at, value.to_f]
result = series[:at].zip(series[:values].map { |v| v.dig(*keys) })
sliced(result: result, slices: slices, block: block)
end

def sliced(result:, slices:, block: nil)
result[(result.count - (result.count / slices * slices))..].each_slice(result.count / slices).map do |slice|
slice.map do |at, value|
block ? block.call(at, value) : [at, value.to_f]
end
end
end
end
Expand Down

0 comments on commit 60219b0

Please sign in to comment.