Home > Net >  bell curve method refactoring
bell curve method refactoring

Time:01-09

Assuming three known attributes:

  • limit (the number of cases on the edge)
  • array of total case ids
  • the focus of analysis (top, middle, bottom)

can the following method be refactored better:

  array_size = ids.size
  if context == 'top'
    ids = ids[0..params[:limit].to_i])
  elsif context == 'bottom'
    ids = ids.pop( ( array_size - params[:limit].to_i ) )
  else
    remove_top = ids.drop( ( params[:limit].to_i / 2).round )
    remove_bottom = ids.pop( ( array_size - (params[:limit].to_i / 2).round ) )
    ids = (ids - ( remove_top   remove_bottom ) ))
  end

CodePudding user response:

my assumptions, based on what you've given us:

  • ids is the array
  • limit is less than the size of the array
  • you meant to have ... instead of .. in your top so that it returns the correct number of elements (elements are numbered from 0)
array_size = ids.size
limit_size = params[:limit].to_i

if context == 'top'
  start_pos = 0
  end_pos = limit_size
elsif context == 'bottom'
  start_pos = array_size - limit_size
  end_pos = array_size
else
  start_pos = (limit_size.to_f/2).ceil
  end_pos = array_size - limit_size/2 - 1
end

ids = ids[start_pos...end_pos]
  •  Tags:  
  • Related