diff --git a/lib/liquid/standardfilters.rb b/lib/liquid/standardfilters.rb index 6855cd212..644967fa1 100644 --- a/lib/liquid/standardfilters.rb +++ b/lib/liquid/standardfilters.rb @@ -193,6 +193,23 @@ def where(input, property, target_value = nil) 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) diff --git a/test/integration/standard_filter_test.rb b/test/integration/standard_filter_test.rb index bf285399e..855514d49 100644 --- a/test/integration/standard_filter_test.rb +++ b/test/integration/standard_filter_test.rb @@ -198,6 +198,12 @@ def test_sort 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_with_nils assert_equal [1, 2, 3, 4, nil], @filters.sort([nil, 4, 3, 2, 1]) assert_equal [{ "a" => 1 }, { "a" => 2 }, { "a" => 3 }, { "a" => 4 }, {}], @filters.sort([{ "a" => 4 }, { "a" => 3 }, {}, { "a" => 1 }, { "a" => 2 }], "a") @@ -292,6 +298,10 @@ def test_sort_natural_empty_array assert_equal [], @filters.sort_natural([], "a") end + def test_sort_numeric_empty_array + assert_equal [], @filters.sort_numeric([], "a") + end + def test_sort_natural_invalid_property foo = [ [1],