-
-
Save andrey-kabakchiev/5772554 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Hash { | |
private $buckets = array(); | |
function put($key, $value) { | |
$this->buckets[$this->generate_hash($key)] = $value; | |
} | |
function get($key) { | |
$hash = $this->generate_hash($key); | |
if (isset($this->buckets[$hash])) { | |
return $this->buckets[$hash]; | |
} | |
return false; | |
} | |
function intval32($value) { | |
if ($value < -2147483648) { | |
return -(-($value) & 0xffffffff); | |
} else if ($value > 2147483647) { | |
return ($value & 0xffffffff); | |
} | |
return $value; | |
} | |
function generate_hash($str) { | |
$hash = 5381; | |
for ($i = 0; $i < strlen($str); $i++) { | |
$hash = $this->intval32(((($hash << 5) + $hash) + ord($str[$i]))); | |
} | |
return $hash; | |
} | |
} | |
$h = new Hash(); | |
$h->put("key1", "Hello World!"); | |
$h->put("key2", "Goodbye World!"); | |
echo $h->get("key1") . PHP_EOL; | |
echo $h->get("key2") . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment