Module: Chartd::Encoder

Defined in:
lib/chartd/encoder.rb

Constant Summary collapse

B62 =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.freeze

Class Method Summary collapse

Class Method Details

.encode(dataset = [], min: nil, max: nil) ⇒ Object

encode encodes a dataset to a format that chartd.co understands. It optionally takes min and max values that change the resulting chart.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/chartd/encoder.rb', line 7

def self.encode(dataset = [], min: nil, max: nil)
  return '' if dataset.empty?

  # either use custom min & max values or take them from the dataset
  min ||= dataset.min
  max ||= dataset.max

  range = dim(max, min)

  # if the range of the data is
  return B62[0] * dataset.count if range == 0

  enclen = B62.length - 1
  encoded = dataset.map do |v|
    index = (enclen * (v - min) / range).to_i

    # TODO: see if else case is even possible
    if index >= 0 && index < B62.length
      B62[index]
    else
      B62[0]
    end
  end

  encoded.join
end