|
1
|
|
|
<?php |
|
2
|
|
|
/* |
|
3
|
|
|
* Copyright (c) Nate Brunette. |
|
4
|
|
|
* Distributed under the MIT License (http://opensource.org/licenses/MIT) |
|
5
|
|
|
*/ |
|
6
|
|
|
|
|
7
|
|
|
namespace Tebru\Collection; |
|
8
|
|
|
|
|
9
|
|
|
use ArrayIterator; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Class HashSet |
|
13
|
|
|
* |
|
14
|
|
|
* An [@see SetInterface] backed by a [@see HashMap] |
|
15
|
|
|
* |
|
16
|
|
|
* @author Nate Brunette <[email protected]> |
|
17
|
|
|
*/ |
|
18
|
|
|
class HashSet extends AbstractSet |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* The data storage |
|
22
|
|
|
* |
|
23
|
|
|
* @var MapInterface |
|
24
|
|
|
*/ |
|
25
|
|
|
protected $map; |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* Constructor |
|
29
|
|
|
* |
|
30
|
|
|
* Use [@see AbstractSet::add] to ensure uniqueness |
|
31
|
|
|
* |
|
32
|
|
|
* @param array $elements |
|
33
|
|
|
*/ |
|
34
|
7 |
|
public function __construct(array $elements = null) |
|
35
|
|
|
{ |
|
36
|
7 |
|
$this->map = new HashMap(); |
|
37
|
|
|
|
|
38
|
7 |
|
if (null !== $elements) { |
|
39
|
6 |
|
$this->addAllArray($elements); |
|
40
|
|
|
} |
|
41
|
7 |
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Adds the element to the collection if it doesn't exist |
|
45
|
|
|
* |
|
46
|
|
|
* @param mixed $element |
|
47
|
|
|
* @return bool |
|
48
|
|
|
*/ |
|
49
|
33 |
|
public function add($element): bool |
|
50
|
|
|
{ |
|
51
|
33 |
|
if ($this->contains($element)) { |
|
52
|
3 |
|
return false; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
33 |
|
$this->map->put($element, true); |
|
56
|
|
|
|
|
57
|
33 |
|
return true; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* Removes all elements from a collection |
|
62
|
|
|
* |
|
63
|
|
|
* @return void |
|
64
|
|
|
*/ |
|
65
|
1 |
|
public function clear() |
|
66
|
|
|
{ |
|
67
|
1 |
|
$this->map->clear(); |
|
68
|
1 |
|
} |
|
69
|
|
|
|
|
70
|
|
|
/** |
|
71
|
|
|
* Removes object if it exists |
|
72
|
|
|
* |
|
73
|
|
|
* Returns true if the element was removed |
|
74
|
|
|
* |
|
75
|
|
|
* @param mixed $element |
|
76
|
|
|
* @return bool |
|
77
|
|
|
*/ |
|
78
|
8 |
|
public function remove($element): bool |
|
79
|
|
|
{ |
|
80
|
8 |
|
$size = $this->map->count(); |
|
81
|
8 |
|
$this->map->remove($element); |
|
82
|
|
|
|
|
83
|
8 |
|
return $size !== $this->map->count(); |
|
84
|
|
|
} |
|
85
|
|
|
|
|
86
|
|
|
/** |
|
87
|
|
|
* Returns an array of all elements in the collection |
|
88
|
|
|
* |
|
89
|
|
|
* @return array |
|
90
|
|
|
*/ |
|
91
|
34 |
|
public function toArray(): array |
|
92
|
|
|
{ |
|
93
|
34 |
|
return $this->map->keys()->toArray(); |
|
94
|
|
|
} |
|
95
|
|
|
|
|
96
|
|
|
/** |
|
97
|
|
|
* Retrieve an external iterator |
|
98
|
|
|
* |
|
99
|
|
|
* @return ArrayIterator |
|
100
|
|
|
*/ |
|
101
|
8 |
|
public function getIterator(): ArrayIterator |
|
102
|
|
|
{ |
|
103
|
8 |
|
return new ArrayIterator($this->toArray()); |
|
104
|
|
|
} |
|
105
|
|
|
} |
|
106
|
|
|
|