trueskill/src/HashMap.php

66 lines
1.2 KiB
PHP
Raw Normal View History

2022-07-05 13:55:47 +00:00
<?php
namespace DNW\Skills;
/**
* Basic hashmap that supports object keys.
*/
class HashMap
{
2023-08-02 13:29:14 +00:00
/**
* @var mixed[] $hashToValue
*/
2023-08-01 13:35:44 +00:00
private array $hashToValue = [];
2022-07-05 13:55:47 +00:00
2023-08-02 13:29:14 +00:00
/**
* @var mixed[] $hashToKey
*/
2023-08-01 13:35:44 +00:00
private array $hashToKey = [];
public function getValue(string|object $key): mixed
{
$hash = self::getHash($key);
2022-07-05 13:55:47 +00:00
2023-08-01 13:35:44 +00:00
return $this->hashToValue[$hash];
}
public function setValue(string|object $key, mixed $value): self
{
$hash = self::getHash($key);
2023-08-01 13:35:44 +00:00
$this->hashToKey[$hash] = $key;
$this->hashToValue[$hash] = $value;
2022-07-05 13:55:47 +00:00
return $this;
}
2023-08-02 13:29:14 +00:00
/**
* @return mixed[]
*/
public function getAllKeys(): array
{
2023-08-01 13:35:44 +00:00
return array_values($this->hashToKey);
}
2023-08-02 13:29:14 +00:00
/**
* @return mixed[]
*/
public function getAllValues(): array
{
2023-08-01 13:35:44 +00:00
return array_values($this->hashToValue);
}
public function count(): int
{
2023-08-01 13:35:44 +00:00
return count($this->hashToKey);
}
2023-08-01 13:35:44 +00:00
private static function getHash(string|object $key): string
{
if (is_object($key)) {
return spl_object_hash($key);
}
return $key;
}
2022-07-05 13:55:47 +00:00
}