intprog_hackery/sorting_algos.rb
2019-10-21 16:22:00 +02:00

39 lines
1.1 KiB
Ruby

# TODO: Make variadic, such that we only need one method
def compare_to(sortings)
first, second, third = *sortings
return_stat = lambda{ |sorting|
if sorting.type == "String"
{:ret => "this.#{sorting.variable}.compareTo(other.#{sorting.variable})"}
else
{:ret => sorting.comparator == ">" ? "this.#{sorting.variable} - other.#{sorting.variable}" : "other.#{sorting.variable} - this.#{sorting.variable}"}
end}
comp = lambda {|sorting|
if sorting.type == "String"
{:if => "!this.#{sorting.variable}.equals(other.#{sorting.variable})",
:ret => (return_stat.call sorting)[:ret]}
else
{:if => "this.#{sorting.variable} != other.#{sorting.variable}",
:ret => (return_stat.call sorting)[:ret]}
end}
pls = sortings.slice(1,sortings.length - 2).map do |ele|
" else if (#{(comp ele)[:if]}) {
return #{(comp ele)[:ret]};
}"
end
"if (#{(comp first)[:if]}) {
return #{(comp first)[:ret]};
}
#{pls.join "\n"}
return #{(comp sortings[sortings.length-1])[:ret]};"
end