Skip to content

Commit 25f4e1f

Browse files
committed
arraylist contains key
1 parent 6f9768b commit 25f4e1f

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

src/Datastructure/Lists/ArrayLists/ArrayList.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,20 @@ public function remove($key): bool {
223223
return false;
224224
}
225225

226+
/**
227+
* whether the array contains $key or not.
228+
*
229+
* @param int $key
230+
* @return bool
231+
*/
232+
public function containsKey(int $key): bool {
233+
$array = $this->array;
234+
$array = \array_filter($array, function ($value, $key) {
235+
return $value !== null;
236+
}, \ARRAY_FILTER_USE_BOTH);
237+
return array_key_exists($key, $array);
238+
}
239+
226240
/**
227241
* removes all elements in the array that are null or equal to empty string
228242
*

tests/Lists/ArrayLists/ArrayListTest.php

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
11
<?php
2-
3-
use doganoo\PHPAlgorithms\Datastructure\Lists\ArrayLists\ArrayList;
4-
52
/**
63
* MIT License
74
*
@@ -25,6 +22,9 @@
2522
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2623
* SOFTWARE.
2724
*/
25+
26+
use doganoo\PHPAlgorithms\Datastructure\Lists\ArrayLists\ArrayList;
27+
2828
class ArrayListTest extends \PHPUnit\Framework\TestCase {
2929
public function testAdd() {
3030
$arrayList = new ArrayList();
@@ -60,6 +60,23 @@ public function testAdd() {
6060
$this->assertTrue($arrayList->length() === 8);
6161
}
6262

63+
public function testContainsKey() {
64+
$arrayList = new ArrayList();
65+
$arrayList->add("five");
66+
$arrayList->add("six");
67+
$arrayList->add("seven");
68+
$arrayList->add("eight");
69+
70+
$this->assertTrue(true === $arrayList->containsKey(0));
71+
$this->assertTrue(true === $arrayList->containsKey(1));
72+
$this->assertTrue(true === $arrayList->containsKey(2));
73+
$this->assertTrue(true === $arrayList->containsKey(3));
74+
$this->assertTrue(false === $arrayList->containsKey(4));
75+
$this->assertTrue(false === $arrayList->containsKey(50));
76+
$this->assertTrue(false === $arrayList->containsKey(150));
77+
78+
}
79+
6380
public function testClear() {
6481
$arrayList = new ArrayList();
6582
$arrayList->add("one");

0 commit comments

Comments
 (0)