Skip to content

Commit

Permalink
fix up percentage option for chart_json
Browse files Browse the repository at this point in the history
  • Loading branch information
ashanbrown committed Oct 10, 2014
1 parent c4f1479 commit c0bfe10
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 6 deletions.
7 changes: 4 additions & 3 deletions lib/chartnado/renderer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,9 @@ def render(*args, **options)
end

def chart_json(series, show_total: false, reverse_sort: false, percentage: false)
series = series_product(100.0, series) if percentage
if series.is_a?(Hash)
series = Chartnado::Series::Wrap[series]
series *= 100.0 if percentage
if series.hash?
if (key = series.keys.first) and key.is_a?(Array) and key.size == 2
totals = Hash.new(0.0)
new_series = series.group_by{|k, v| k[0] }.sort_by { |k| k.to_s }
Expand Down Expand Up @@ -82,7 +83,7 @@ def chart_json(series, show_total: false, reverse_sort: false, percentage: false
new_series
end
end
elsif series.is_a?(Array) && series.first.is_a?(Array)
elsif series.array? && series.first.is_a?(Array)
if series.first.second.respond_to?(:map)
totals = Hash.new(0.0)
new_series = series.sort_by { |item| item.first.to_s }
Expand Down
8 changes: 5 additions & 3 deletions lib/chartnado/series/wrap.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ def times(factor, precision: 2)
return __getobj__ unless length > 0

if array_of_named_series? || array? && first.is_a?(Array)
map { |(name, data)| [name, wrap(data) * factor] }
result = map { |(name, data)| [name, wrap(data) * factor] }
elsif hash?
to_a.reduce({}) do |hash, (key, value)|
result = to_a.reduce({}) do |hash, (key, value)|
if factor.hash?
if key.is_a?(Array)
scalar = factor[key.second]
Expand All @@ -34,10 +34,12 @@ def times(factor, precision: 2)
hash
end
else
map do |value|
result = map do |value|
factor * value
end
end

wrap(result)
end

def add(*series, scalar_sum: 0.0)
Expand Down
6 changes: 6 additions & 0 deletions spec/renderer_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ def chart_json(*series, **options)
{name: :a, data: [[1, 10]]},
{name: :b, data: [[1, 20]]}]
end
it "can add multiply by 100 to create a percentage" do
expect(chart_json({[:a, 1] => 0.1, [:b, 1] => 0.2}, percentage: true, show_total: true)).
to eq [{name: 'Total', data: [[1, 0]], tooltip: [[1, 30.0]]},
{name: :a, data: [[1, 10.0]]},
{name: :b, data: [[1, 20.0]]}]
end
describe "with multiple scalar series" do
it "can handle scalars" do
expect(chart_json({:a => 10, :b => 20})).
Expand Down

0 comments on commit c0bfe10

Please sign in to comment.