File tree 2 files changed +44
-0
lines changed
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 {
372
372
return $ array ;
373
373
}
374
374
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
+
375
389
/**
376
390
* basic implementation of Java-like keySet().
377
391
* The method returns an array containing the node keys.
Original file line number Diff line number Diff line change 27
27
namespace doganoo \PHPAlgorithmsTest \Table ;
28
28
29
29
use doganoo \PHPAlgorithms \Common \Interfaces \IHashable ;
30
+ use doganoo \PHPAlgorithms \Datastructure \Lists \ArrayList \ArrayList ;
30
31
use doganoo \PHPAlgorithms \Datastructure \Table \HashTable ;
31
32
use doganoo \PHPAlgorithmsTest \Table \Entity \HashableObject ;
32
33
use doganoo \PHPAlgorithmsTest \Util \HashTableUtil ;
@@ -145,6 +146,35 @@ public function testKeyTypes(): void {
145
146
$ this ->assertTrue ($ added );
146
147
}
147
148
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
+
148
178
/**
149
179
* tests retrieving all keys from the map
150
180
*/
You can’t perform that action at this time.
0 commit comments