Reputation: 6873
I have a couple scenarios where a series of arbitrary string values have a specific priority sequence. For example:
forgo > log > assert
exception > failure > error > warning > alert
And, I need to evaluate an arbitrary number of scenarios that resolve to one of those values and maintain a running status. So, using the simpler example, if every evaluation is assert
then the final running status would be assert
. But if a single evaluation is log
and the rest are assert
, the the final running status is log
. And a single forgo
means the final status is forgo
, no matter what the mix of individual status results was. I want to provide a human readable running status and individual status, do the math to determine what the new running index is, then return the human readable status.
So, I have this, and it works.
$statusIndex = @('assert', 'log', 'forgo')
$runningStatus = 'forgo'
$individualStatus = 'log'
$runningStatusIndex = $statusIndex.indexof($runningStatus)
$individualStatusIndex = $statusIndex.indexof($individualStatus)
if ($individualStatusIndex -gt $runningStatusIndex) {
$runningStatusIndex = $individualStatusIndex
}
$runningStatus = $statusIndex[$runningStatusIndex]
But, this feels like something that happens often enough that there may be a more "native" way to do it. Some built in PowerShell functionality that handles the same thing more elegantly and in less code.
Is my intuition correct, and there is a native way? Or, perhaps a more elegant approach than what I have here?
Upvotes: 1
Views: 53
Reputation: 174760
Put your terms in an array, in precedence order:
$statusIndex = @('forgo', 'log', 'assert')
Aggregate all your status values and remove any duplicates:
$statusValues = 'assert', 'assert', 'log', 'assert'
$statusValueSet = $statusValues |Sort -Unique
Now use the .Where()
extension method to select only the first matching term from the precedence list:
$overallStatus = $statusIndex.Where({$_ -in $statusValueSet}, 'First')
Value of $overallStatus
should now be 'log'
as expected.
3-4 lines of code instead of 9-10 :)
Upvotes: 1