Skip to content

Instantly share code, notes, and snippets.

@Abhinav1217
Created March 29, 2022 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Abhinav1217/8014e8c8e9a2fbaf217b20216adfccbc to your computer and use it in GitHub Desktop.
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.
<?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