Created
March 29, 2022 07:59
-
-
Save Abhinav1217/8014e8c8e9a2fbaf217b20216adfccbc to your computer and use it in GitHub Desktop.
Simple Implementation of HashSet in php for quick hacks. Not recommended in actual works.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class HashSet | |
{ | |
// PHP arrays are organized trees under the hood, also php provides better api's for dealing with keys. | |
// Hence we will use an arrays use it's keys for storing our nodes. Note PHP Arrays are always associative arrays. | |
private $set = []; | |
public function __construct($keys = []) | |
{ | |
$this->add($keys); | |
} | |
public function __destruct() | |
{ | |
unset($this->set); | |
} | |
public function add($key) | |
{ | |
if(!is_array($key)) | |
{ | |
$keys = [$key => null]; | |
} | |
else | |
{ | |
$keys = array_combine($key, array_fill(on count($key), null)); | |
} | |
$this->set += $keys; | |
} | |
public function remove($key) | |
{ | |
if (!is_array($key)) | |
{ | |
unser($this->set[$key]); | |
} | |
else | |
{ | |
foreach ($key as $singleKey) | |
{ | |
unser($this->set[$singleKey]); | |
} | |
} | |
} | |
public function contains($key) | |
{ | |
return array_key_exists($key, $this->set); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment