Skip to content

Instantly share code, notes, and snippets.

@vexx32
Last active May 3, 2019 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vexx32/6b3e7350f24106c7c1599cca857bb2e7 to your computer and use it in GitHub Desktop.
Save vexx32/6b3e7350f24106c7c1599cca857bb2e7 to your computer and use it in GitHub Desktop.
# Simple approach - let PS's type conversion logic handle it.
# Pitfall: someone can just supply arbitrary text to the function, which is a bit unfortunate.
function Get-Factorial {
param($Number)
if ($Number -eq 0) {
1
}
else {
$Number * (Get-Factorial -Number ($Number - 1))
}
}
# More robust approach: type cast the parameter itself
# Pitfall: No handling of negative numbers, will cause infinite loops
function Get-Factorial {
param(
[int]
$Number
)
if ($Number -eq 0) {
1
}
else {
$Number * (Get-Factorial -Number ($Number - 1))
}
}
# Strict approach: prevent negatives with parameter attributes,
# and prevent extra values being passed in arbitrarily with [CmdletBinding()]
function Get-Factorial {
[CmdletBinding()]
param(
[Parameter(Mandatory, Position = 0)]
[ValidateRange(0, [int]::MaxValue)]
[int]
$Number
)
if ($Number -eq 0) {
1
}
else {
$Number * (Get-Factorial -Number ($Number - 1))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment