Module: LabTech::Percentile

Extended by:
Percentile
Included in:
Percentile
Defined in:
app/models/lab_tech/percentile.rb

Constant Summary collapse

MIN_PERCENTILE =
0
MAX_PERCENTILE =
100

Instance Method Summary collapse

Instance Method Details

#call(pct, list) ⇒ Object

Raises:

  • (ArgumentError)


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'app/models/lab_tech/percentile.rb', line 8

def call(pct, list)
  # Make sure this list is actually sorted
  unless sorted?(list)
    fail "Sorry, this isn't sorted: #{list.inspect}"
  end

  msg = "Please pass an integer between #{MIN_PERCENTILE} and #{MAX_PERCENTILE}, not #{pct.inspect}"
  raise ArgumentError, msg unless pct.kind_of?(Integer)
  raise ArgumentError, msg unless (MIN_PERCENTILE..MAX_PERCENTILE).cover?(pct)

  return list.first if pct == MIN_PERCENTILE # Avoid the need for a bounds check later
  return list.last  if pct == MAX_PERCENTILE # By definition, I guess

  i = ( 0.01 * pct * list.length ).ceil - 1 # Don't ask me why this works
  list[ i ]
end