# 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