From 99cb3cf5aa608e09b507bac956213067c1fa83fc Mon Sep 17 00:00:00 2001 From: Dmytro Sokil Date: Fri, 28 Nov 2014 22:38:20 +0200 Subject: [PATCH] get keys --- src/PriorityList.php | 5 +++++ src/WeightList.php | 17 +++++++++++------ tests/PriorityListTest.php | 16 ++++++++++++++++ 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/src/PriorityList.php b/src/PriorityList.php index fdbdf64..a813891 100644 --- a/src/PriorityList.php +++ b/src/PriorityList.php @@ -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); diff --git a/src/WeightList.php b/src/WeightList.php index 1fb623e..29020a3 100644 --- a/src/WeightList.php +++ b/src/WeightList.php @@ -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; @@ -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); + } } \ No newline at end of file diff --git a/tests/PriorityListTest.php b/tests/PriorityListTest.php index 15ea9b1..3594351 100644 --- a/tests/PriorityListTest.php +++ b/tests/PriorityListTest.php @@ -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();