As an experiment with PowerShell 5.0 classes I tried to translate JavaScript code for the Stable Marriage problem at Rosetta Code. It seemed very straight forward, but The second method (Rank) returns the error: Not all code path returns value within method.
class Person
{
# --------------------------------------------------------------- Properties
hidden [int]$CandidateIndex = 0
[string]$Name
[person]$Fiance = $null
[person[]]$Candidates = @()
# ------------------------------------------------------------- Constructors
Person ([string]$Name)
{
$this.Name = $Name
}
# ------------------------------------------------------------------ Methods
static [void] AddCandidates ([person[]]$Candidates)
{
[Person]::Candidates = $Candidates
}
[int] Rank ([person]$Person)
{
for ($i = 0; $i -lt $this.Candidates.Count; $i++)
{
if ($this.Candidates[$i] -eq $Person)
{
return $i
}
return $this.Candidates.Count + 1
}
}
[bool] Prefers ([person]$Person)
{
return $this.Rank($Person) -lt $this.Rank($this.Fiance)
}
[person] NextCandidate ()
{
if ($this.CandidateIndex -ge $this.Candidates.Count)
{
return $null
}
return $this.Candidates[$this.CandidateIndex++]
}
[int] EngageTo ([person]$Person)
{
if ($Person.Fiance)
{
$Person.Fiance.Fiance = $null
}
return $this.Fiance = $Person
}
[void] SwapWith ([person]$Person)
{
Write-Host ("{0} and {1} swap partners" -f $this.Name, $Person.Name)
$thisFiance = $this.Fiance
$personFiance = $Person.Fiance
$this.EngageTo($personFiance)
$Person.EngageTo($thisFiance)
}
}