File tree Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Original file line number Diff line number Diff 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.
Original file line number Diff line number Diff line change 2727namespace doganoo \PHPAlgorithmsTest \Table ;
2828
2929use doganoo \PHPAlgorithms \Common \Interfaces \IHashable ;
30+ use doganoo \PHPAlgorithms \Datastructure \Lists \ArrayList \ArrayList ;
3031use doganoo \PHPAlgorithms \Datastructure \Table \HashTable ;
3132use doganoo \PHPAlgorithmsTest \Table \Entity \HashableObject ;
3233use 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 */
You can’t perform that action at this time.
0 commit comments