Looking at the results in python at http://try-python.mired.org/, it appears that the correct algorithm splits at word boundaries, rather than taking fixed-length substrings from the text.
function wrap( [string]$text, [int]$width = 70 ) {
$line = ''
# Split the text into words.
$text.Split( ' '.ToCharArray( ) ) | % {
# Initialize the first line with the first word.
if( -not $line ) { $line = $_ }
else {
# For each new word, try to add it to the current line.
$next = $line + ' ' + $_
# If the new word goes over the limit,
# return the last line and start a new one.
if( $next.Length -ge $width ) { $line; $line = $_ }
# Otherwise, use the updated line with the new word.
else { $line = $next }
}
}
# Return the last line, containing the remainder of the text.
$line
}
And here's an alternate implementation for dedent
as well.
function dedent( [string[]]$lines ) {
# Find the shortest length of leading whitespace common to all lines.
$commonLength = (
$lines | % {
$i = 0
while( $i -lt $_.Length -and [char]::IsWhitespace( $_, $i ) ) { ++$i }
$i
} | Measure-Object -minimum
).Minimum
# Remove the common whitespace from each string
$lines | % { $_.Substring( $commonLength ) }
}
Hopefully their greater verbosity will provide better clarity :)