diff --git a/History.md b/History.md index a8c8854..d1f90fa 100644 --- a/History.md +++ b/History.md @@ -3,6 +3,7 @@ ## 3.0.0 / not yet released / branch "master" * ... +* Add uniq to standard filters [Florian Weingarten, fw42] * Add exception_handler feature, see #397 and #254 [Bogdan Gusiev, bogdan and Florian Weingarten, fw42] * Optimize variable parsing to avoid repeated regex evaluation during template rendering #383 [Jason Hiltz-Laforge, jasonhl] * Optimize checking for block interrupts to reduce object allocation #380 [Jason Hiltz-Laforge, jasonhl] diff --git a/lib/liquid/standardfilters.rb b/lib/liquid/standardfilters.rb index 0a956fb..9bf209a 100644 --- a/lib/liquid/standardfilters.rb +++ b/lib/liquid/standardfilters.rb @@ -101,13 +101,24 @@ module Liquid ary = InputIterator.new(input) if property.nil? ary.sort - elsif ary.first.respond_to?('[]'.freeze) && !ary.first[property].nil? + elsif ary.first.respond_to?(:[]) && !ary.first[property].nil? ary.sort {|a,b| a[property] <=> b[property] } elsif ary.first.respond_to?(property) ary.sort {|a,b| a.send(property) <=> b.send(property) } end end + # Remove duplicate elements from an array + # provide optional property with which to determine uniqueness + def uniq(input, property = nil) + ary = InputIterator.new(input) + if property.nil? + input.uniq + elsif input.first.respond_to?(:[]) + input.uniq{ |a| a[property] } + end + end + # Reverse the elements of an array def reverse(input) ary = InputIterator.new(input) diff --git a/test/integration/standard_filter_test.rb b/test/integration/standard_filter_test.rb index fc6b600..56ef72a 100644 --- a/test/integration/standard_filter_test.rb +++ b/test/integration/standard_filter_test.rb @@ -128,6 +128,13 @@ class StandardFiltersTest < Minitest::Test assert_equal [{"a" => "10"}, {"a" => "2"}], @filters.sort([{"a" => "10"}, {"a" => "2"}], "a") end + def test_uniq + assert_equal [1,3,2,4], @filters.uniq([1,1,3,2,3,1,4,3,2,1]) + assert_equal [{"a" => 1}, {"a" => 3}, {"a" => 2}], @filters.uniq([{"a" => 1}, {"a" => 3}, {"a" => 1}, {"a" => 2}], "a") + testdrop = TestDrop.new + assert_equal [testdrop], @filters.uniq([testdrop, TestDrop.new], 'test') + end + def test_reverse assert_equal [4,3,2,1], @filters.reverse([1,2,3,4]) end