Skip to content

Commit

Permalink
uniq accepts iterator
Browse files Browse the repository at this point in the history
  • Loading branch information
brianhaveri committed Aug 3, 2011
1 parent 73c4ef2 commit ab02d08
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
13 changes: 13 additions & 0 deletions test/ArraysTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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"');
Expand Down
14 changes: 10 additions & 4 deletions underscore.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down

0 comments on commit ab02d08

Please sign in to comment.