ENHANCEMENT: Added ArrayList->removeDuplicates().

This commit is contained in:
ajshort 2011-05-05 20:53:07 +10:00
parent 99a2baf3f8
commit 462689a4e6
2 changed files with 39 additions and 0 deletions

View File

@ -90,6 +90,26 @@ class ArrayList extends ViewableData implements SS_List {
foreach ($with as $item) $this->push($item);
}
/**
* Removes items from this list which have a duplicate value for a certain
* field. This is especially useful when combining lists.
*
* @param string $field
*/
public function removeDuplicates($field = 'ID') {
$seen = array();
foreach ($this->array as $key => $item) {
$value = $this->extract($item, $field);
if (array_key_exists($value, $seen)) {
unset($this->array[$key]);
}
$seen[$value] = true;
}
}
/**
* Pushes an item onto the end of this list.
*

View File

@ -90,6 +90,25 @@ class ArrayListTest extends SapphireTest {
));
}
public function testRemoveDuplicates() {
$list = new ArrayList(array(
array('ID' => 1, 'Field' => 1),
array('ID' => 2, 'Field' => 2),
array('ID' => 3, 'Field' => 3),
array('ID' => 4, 'Field' => 1),
(object) array('ID' => 5, 'Field' => 2)
));
$this->assertEquals(5, count($list));
$list->removeDuplicates();
$this->assertEquals(5, count($list));
$list->removeDuplicates('Field');
$this->assertEquals(3, count($list));
$this->assertEquals(array(1, 2, 3), $list->column('Field'));
$this->assertEquals(array(1, 2, 3), $list->column('ID'));
}
public function testPushPop() {
$list = new ArrayList(array('Num' => 1));
$this->assertEquals(1, count($list));