Skip to content

Instantly share code, notes, and snippets.

@idavis
Created August 10, 2012 15:03
Show Gist options
  • Select an option

  • Save idavis/3314814 to your computer and use it in GitHub Desktop.

Select an option

Save idavis/3314814 to your computer and use it in GitHub Desktop.
Parametric Polymorphism in PowerShell, but in a single method o.O
$point = new-object psobject
$point | Add-Member NoteProperty -Name X -Value 4
$point | Add-Member NoteProperty -Name Y -Value 0
$point2 = new-object psobject
$point2 | Add-Member NoteProperty -Name X -Value 0
$point2 | Add-Member NoteProperty -Name Y -Value 0
function Get-Distance {
param(
[Parameter(Position=0,Mandatory=$True)]
[psobject]$origin,
[Parameter(Position=1,Mandatory=$True,ParameterSetName="point")]
[psobject]$point,
[Parameter(Position=1,Mandatory=$True,ParameterSetName='xy')]
[int]$x,
[Parameter(Position=2,Mandatory=$True,ParameterSetName='xy')]
[int]$y
)
switch ($PsCmdlet.ParameterSetName)
{
"point" {
return [Math]::Sqrt( [Math]::Pow(($origin.x - $point.x),2) + [Math]::Pow(($origin.y - $point.y),2))
}
"xy" {
return [Math]::Sqrt( [Math]::Pow(($origin.x - $x),2) + [Math]::Pow(($origin.y - $y),2))
}
}
}
Get-Distance $point $point2
Get-Distance $point 0 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment