Sha256: a8c79ba70d97155829c87d39ea558146f834bbf97dd3da46892d5f6e51dca97c

Contents?: true

Size: 1.21 KB

Versions: 1

Compression:

Stored size: 1.21 KB

Contents

# frozen_string_literal: true

module Lexoranking
  # Main class that calculates the ranking value based on
  # some previous and next elements.
  class Main
    class InvalidRankError < StandardError; end

    MIN_CHAR = "a"
    MAX_CHAR = "z"

    class << self
      def perform(prev, after)
        new(prev, after).calculate_ranking
      end
    end

    def initialize(prev, after)
      @prev = prev || MIN_CHAR
      @after = after || MAX_CHAR
    end

    def calculate_ranking
      rank = ""
      i = 0

      loop do
        prev_char = get_char(prev, i, MIN_CHAR)
        after_char = get_char(after, i, MAX_CHAR)

        if prev_char == after_char
          rank += prev_char
          i += 1
          next
        end

        mid_char = mid(prev_char, after_char)
        if mid_char == prev_char || mid_char == after_char
          rank += prev_char
          i += 1
          next
        end

        rank += mid_char
        break
      end

      rank
    end

    def mid(prev, after)
      middle_ascii = ((prev.ord + after.ord) / 2).round
      middle_ascii.chr
    end

    def get_char(str, idx, default_char)
      idx >= str.length ? default_char : str[idx]
    end

    attr_accessor :prev, :after
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
lexoranking-0.1.3 lib/lexoranking/main.rb