G'day
While in strict mode, is there a way to search a Map via value rather than key?
Say I have a Map:
$temp = Map{'melon', 'apple'};
How could I search via value?
First, the Map in your example isn't a valid Map. Maps in Hack are key-value pairs, and you only provided keys. I assume this is a typo, and the example you meant to give was something like
$temp = Map {'fruit' => 'apple', 'veg' => 'carrot'};
To search a map in Hack, you can do the same thing you would in PHP: iterate over it in an O(n) scan. Here's an example function that does so, written with Hack generics so it will have the right type no matter the input Map.
function find_key<Tk, Tv>(Map<Tk, Tv> $haystack, Tv $needle): ?Tk {
foreach ($haystack as $k => $v) {
if ($v === $needle) {
return $k;
}
}
return null;
}
However, a final question back to you: why are you searching a Map like this? Maps were meant to have fast value lookup for a given key, as well as fast iteration over all key/value pairs. They are not designed for value lookup like this -- that's why it takes an O(n) loop, which should set off warning signs that what you're doing might not be the best. You may want to consider using a more appropriate data structure: maybe building an inverse map if you're doing this operation often, or using a Set or a Vector depending.