From ab02d08827a926d395560f57e6779dbf50dd5825 Mon Sep 17 00:00:00 2001 From: Brian Haveri Date: Wed, 3 Aug 2011 10:52:50 -0600 Subject: [PATCH] uniq accepts iterator --- test/ArraysTest.php | 13 +++++++++++++ underscore.php | 14 ++++++++++---- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/test/ArraysTest.php b/test/ArraysTest.php index 20ebae2..d7757ca 100644 --- a/test/ArraysTest.php +++ b/test/ArraysTest.php @@ -132,6 +132,19 @@ public function testUniq() { $result = $func(1,2,1,3,1,4); $this->assertEquals(array(1,2,3,4), $result, 'works on an arguments object'); + $list = array( + (object) array('name'=>'moe'), + (object) array('name'=>'curly'), + (object) array('name'=>'larry'), + (object) array('name'=>'curly') + ); + $iterator = function($value) { return $value->name; }; + $this->assertEquals(array('moe', 'curly', 'larry'), __::map(__::uniq($list, false, $iterator), $iterator), 'can find the unique values of an array using a custom iterator'); + + $iterator = function($value) { return $value + 1; }; + $list = array(1, 2, 2, 3, 4, 4); + $this->assertEquals(array(1, 2, 3, 4), __::uniq($list, true, $iterator), 'iterator works with sorted array'); + // extra $this->assertEquals(array(4,5,6), __(array(4,5,4,4,5,5,6))->uniq(), 'works with OO call'); $this->assertEquals(array(4,5,6), __(array(4,5,4,4,5,5,6))->unique(), 'aliased as "unique"'); diff --git a/underscore.php b/underscore.php index 4239b99..0692cf0 100644 --- a/underscore.php +++ b/underscore.php @@ -325,18 +325,24 @@ public function without($collection=null, $val=null) { // Return an array of the unique values // uniq alias: unique - public function unique($collection=null) { return self::uniq($collection); } - public function uniq($collection=null) { - list($collection) = self::_wrapArgs(func_get_args(), 1); + public function unique($collection=null, $is_sorted=null, $iterator=null) { return self::uniq($collection, $is_sorted, $iterator); } + public function uniq($collection=null, $is_sorted=null, $iterator=null) { + list($collection, $is_sorted, $iterator) = self::_wrapArgs(func_get_args(), 3); $collection = self::_collection($collection); $return = array(); if(count($collection) === 0) return self::_wrap($return); + $calculated = array(); foreach($collection as $item) { - if(is_bool(array_search($item, $return, true))) $return[] = $item; + $val = (!is_null($iterator)) ? $iterator($item) : $item; + if(is_bool(array_search($val, $calculated, true))) { + $calculated[] = $val; + $return[] = $item; + } } + return self::_wrap($return); }