Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions lib/liquid2/filters/sort.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
module Liquid2
# Liquid filters and helper methods.
module Filters
INFINITY_ARRAY = [Float::INFINITY].freeze # : [Float]

def self.sort(left, key = nil, context:)
left = Liquid2::Filters.to_enumerable(left)

Expand Down Expand Up @@ -82,12 +84,11 @@ def self.numeric_compare(left, right)
end

def self.ints(obj)
case obj
when Integer, Float, BigDecimal
if obj.is_a?(Integer) || obj.is_a?(Float) || obj.is_a?(BigDecimal)
[obj]
else
numeric = obj.to_s.scan(/-?\d+/)
return [Float::INFINITY] if numeric.empty?
numeric = obj.to_s.scan(/(?<=\.)0+|-?\d+/)
return INFINITY_ARRAY if numeric.empty?

numeric.map(&:to_i)
end
Expand Down
2 changes: 2 additions & 0 deletions sig/liquid2.rbs
Original file line number Diff line number Diff line change
Expand Up @@ -1760,6 +1760,8 @@ module Liquid2

def self.nil_safe_casecmp: (untyped a, untyped b) -> (0 | 1 | -1)

INFINITY_ARRAY: [Float]

def self.numeric_compare: (untyped left, untyped right) -> (0 | 1 | -1)

def self.ints: (untyped obj) -> Array[(Integer | Float | BigDecimal)]
Expand Down
7 changes: 7 additions & 0 deletions test/test_sort_numeric.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ def test_array_of_floats
assert_equal([1.01, 1.1, 2.3, 3.5, 10.1], sorted)
end

def test_array_of_string_floats
left = ["10.1", "3.5", "2.3", "1.1", "1.01"]
sorted = Liquid2::Filters.sort_numeric(left, context: MOCK_RENDER_CONTEXT)

assert_equal(["1.01", "1.1", "2.3", "3.5", "10.1"], sorted)
end

def test_negative_strings
left = ["1", "-1"]
sorted = Liquid2::Filters.sort_numeric(left, context: MOCK_RENDER_CONTEXT)
Expand Down