mirror of
https://github.com/Shopify/liquid.git
synced 2026-09-15 08:50:45 -07:00
Add sort_numeric filter
This commit is contained in:
@@ -151,6 +151,23 @@ module Liquid
|
||||
end
|
||||
end
|
||||
|
||||
# Sort elements of an array in numeric order
|
||||
# provide optional property with which to sort an array of hashes or drops
|
||||
def sort_numeric(input, property = nil)
|
||||
ary = InputIterator.new(input)
|
||||
if property.nil?
|
||||
ary.sort do |a, b|
|
||||
Utils.to_number(a) <=> Utils.to_number(b)
|
||||
end
|
||||
elsif ary.empty? # The next two cases assume a non-empty array.
|
||||
[]
|
||||
elsif ary.first.respond_to?(:[]) && !ary.first[property].nil?
|
||||
ary.sort do |a, b|
|
||||
Utils.to_number(a[property]) <=> Utils.to_number(b[property])
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Remove duplicate elements from an array
|
||||
# provide optional property with which to determine uniqueness
|
||||
def uniq(input, property = nil)
|
||||
|
||||
@@ -190,6 +190,13 @@ class StandardFiltersTest < Minitest::Test
|
||||
assert_equal [{ "a" => 1 }, { "a" => 2 }, { "a" => 3 }, { "a" => 4 }], @filters.sort([{ "a" => 4 }, { "a" => 3 }, { "a" => 1 }, { "a" => 2 }], "a")
|
||||
end
|
||||
|
||||
def test_sort_numeric
|
||||
assert_equal ['1', '2', '3', '10'], @filters.sort_numeric(['10', '3', '2', '1'])
|
||||
|
||||
assert_equal [{ "a" => '1' }, { "a" => '2' }, { "a" => '3' }, { "a" => '10' }],
|
||||
@filters.sort_numeric([{ "a" => '10' }, { "a" => '3' }, { "a" => '1' }, { "a" => '2' }], "a")
|
||||
end
|
||||
|
||||
def test_sort_when_property_is_sometimes_missing_puts_nils_last
|
||||
input = [
|
||||
{ "price" => 4, "handle" => "alpha" },
|
||||
@@ -216,6 +223,10 @@ class StandardFiltersTest < Minitest::Test
|
||||
assert_equal [], @filters.sort_natural([], "a")
|
||||
end
|
||||
|
||||
def test_sort_numeric_empty_array
|
||||
assert_equal [], @filters.sort_numeric([], "a")
|
||||
end
|
||||
|
||||
def test_legacy_sort_hash
|
||||
assert_equal [{ a: 1, b: 2 }], @filters.sort({ a: 1, b: 2 })
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user