Skip to content

Commit

Permalink
get keys
Browse files Browse the repository at this point in the history
  • Loading branch information
sokil committed Nov 28, 2014
1 parent b735972 commit 99cb3cf
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 6 deletions.
5 changes: 5 additions & 0 deletions src/PriorityList.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ public function has($name)
return isset($this->list[$name]);
}

public function getKeys()
{
return array_keys($this->list);
}

public function count()
{
return count($this->list);
Expand Down
17 changes: 11 additions & 6 deletions src/WeightList.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,25 @@
namespace Sokil\DataType;

/**
* Class used to get some identifier according to
* Class used to get some identifier according to
* probability of this key.
*
*
*/
class WeightList
{
private $list;

public function __construct(array $list = array())
{
$this->list = $list;
}

public function set($value, $weight)
{
$this->list[$value] = $weight;
return $this;
}

private function getValueByPosition($position)
{
$accumulator = 0;
Expand All @@ -34,10 +34,15 @@ private function getValueByPosition($position)

return $value;
}

public function getRandomValue()
{
$position = mt_rand(0, array_sum($this->list));
return $this->getValueByPosition($position);
}

public function getValues()
{
return array_keys($this->list);
}
}
16 changes: 16 additions & 0 deletions tests/PriorityListTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,22 @@ public function testGet()
$this->assertEquals('v5', $list->get('k5'));
}

public function testGetKeys()
{
$list = new PriorityList();

$list->set('k1', 'v1', 2);
$list->set('k2', 'v2', 8);
$list->set('k3', 'v3', 16);
$list->set('k4', 'v4', 1);
$list->set('k5', 'v5', 4);

$this->assertEquals(
array('k1', 'k2', 'k3', 'k4', 'k5'),
$list->getKeys()
);
}

public function testHas()
{
$list = new PriorityList();
Expand Down

0 comments on commit 99cb3cf

Please sign in to comment.