Skip to content

Commit a0c855e

Browse files
committed
add static method fromIterable
1 parent db338e7 commit a0c855e

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/Datastructure/Table/HashTable.php

+14
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,20 @@ public function toArray(): array {
372372
return $array;
373373
}
374374

375+
/**
376+
* @param iterable $iterable
377+
* @return HashTable
378+
* @throws InvalidKeyTypeException
379+
* @throws UnsupportedKeyTypeException
380+
*/
381+
public static function fromIterable(iterable $iterable): HashTable {
382+
$hashTable = new HashTable();
383+
foreach ($iterable as $key => $value) {
384+
$hashTable->put($key, $value);
385+
}
386+
return $hashTable;
387+
}
388+
375389
/**
376390
* basic implementation of Java-like keySet().
377391
* The method returns an array containing the node keys.

tests/Table/HashTableTest.php

+30
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
namespace doganoo\PHPAlgorithmsTest\Table;
2828

2929
use doganoo\PHPAlgorithms\Common\Interfaces\IHashable;
30+
use doganoo\PHPAlgorithms\Datastructure\Lists\ArrayList\ArrayList;
3031
use doganoo\PHPAlgorithms\Datastructure\Table\HashTable;
3132
use doganoo\PHPAlgorithmsTest\Table\Entity\HashableObject;
3233
use doganoo\PHPAlgorithmsTest\Util\HashTableUtil;
@@ -145,6 +146,35 @@ public function testKeyTypes(): void {
145146
$this->assertTrue($added);
146147
}
147148

149+
/**
150+
* tests adding different key types to the map
151+
*/
152+
public function testFromIterable(): void {
153+
$array = [1, 2, 3];
154+
$hashTable = HashTable::fromIterable($array);
155+
156+
$this->assertTrue($hashTable->size() === 3);
157+
$this->assertTrue($hashTable->get(0) === 1);
158+
$this->assertTrue($hashTable->get(1) === 2);
159+
$this->assertTrue($hashTable->get(2) === 3);
160+
}
161+
162+
/**
163+
* tests adding different key types to the map
164+
*/
165+
public function testFromIterableArrayList(): void {
166+
$arrayList = new ArrayList();
167+
$arrayList->add(1);
168+
$arrayList->add(2);
169+
$arrayList->add(3);
170+
$hashTable = HashTable::fromIterable($arrayList);
171+
172+
$this->assertTrue($hashTable->size() === 3);
173+
$this->assertTrue($hashTable->get(0) === 1);
174+
$this->assertTrue($hashTable->get(1) === 2);
175+
$this->assertTrue($hashTable->get(2) === 3);
176+
}
177+
148178
/**
149179
* tests retrieving all keys from the map
150180
*/

0 commit comments

Comments
 (0)