Sorting support for data with undefined values

This commit is contained in:
Eric Chan
2017-09-14 02:00:43 -04:00
parent cfe1844de9
commit deb10ebc7a
2 changed files with 35 additions and 8 deletions

View File

@@ -121,17 +121,23 @@ module Liquid
def sort(input, property = nil)
ary = InputIterator.new(input)
if property.nil?
ary.sort
ary.sort do |a, b|
if !a.nil? && !b.nil?
a <=> b
else
a.nil? ? 1 : -1
end
end
elsif ary.empty? # The next two cases assume a non-empty array.
[]
elsif ary.first.respond_to?(:[]) && !ary.first[property].nil?
elsif ary.all? { |el| el.respond_to?(:[]) }
ary.sort do |a, b|
a = a[property]
b = b[property]
if a && b
if !a.nil? && !b.nil?
a <=> b
else
a ? -1 : 1
a.nil? ? 1 : -1
end
end
end
@@ -143,17 +149,23 @@ module Liquid
ary = InputIterator.new(input)
if property.nil?
ary.sort { |a, b| a.to_s.casecmp(b.to_s) }
ary.sort do |a, b|
if !a.nil? && !b.nil?
a.to_s.casecmp(b.to_s)
else
a.nil? ? 1 : -1
end
end
elsif ary.empty? # The next two cases assume a non-empty array.
[]
elsif ary.first.respond_to?(:[]) && !ary.first[property].nil?
elsif ary.all? { |el| el.respond_to?(:[]) }
ary.sort do |a, b|
a = a[property]
b = b[property]
if a && b
if !a.nil? && !b.nil?
a.to_s.casecmp(b.to_s)
else
a ? -1 : 1
a.nil? ? 1 : -1
end
end
end