Last active
July 27, 2024 11:10
-
-
Save gabriel-vanca/9ac9c5faeb098ce60dafef0de10d8245 to your computer and use it in GitHub Desktop.
Search-HashTable
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
<# | |
.SYNOPSIS | |
This function performs a search of a hash table using a provided key. | |
.DESCRIPTION | |
This function performs a search of a hash table using a provided key. | |
It returns the value matching the key if found, and null otherwise. | |
The case sensitive search has O(1) time complexity while the case insensitive search has | |
O(N) time complexity, where N is the number of key-value pairs in the hash table. | |
#> | |
function Search-HashTable { | |
[CmdletBinding()] | |
param ( | |
# The hash table | |
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)] | |
[ValidateNotNull()] | |
[HashTable]$hashTable, | |
# The key used to lookup the value in the hash table | |
[Parameter(Mandatory=$true, Position=1)] | |
[ValidateNotNullOrEmpty()] | |
[String]$key, | |
# Select if the search should be case sensitive. | |
[Parameter(Mandatory=$false, Position=2)] | |
[Switch]$caseSensitive | |
) | |
if ($caseSensitive) { | |
# Case sensitive search | |
if($hashTable.ContainsKey($key)) { | |
return $hashTable.$key | |
} else { | |
return $NULL | |
} | |
} else { | |
# Case insensitive search | |
foreach ($keyValuePair in $hashTable.GetEnumerator()) { | |
# String comparisons are case insensitive | |
if ($key -eq $keyValuePair.Key) { | |
return $keyValuePair.Value | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment