Powershell Text Flip

Here’s a fun piece of code. All it does is take a string, and turn it over.

function Flip-Text
{
    [CmdLetBinding()]
    param
    (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)][String]$text
    )
    process
    {
        $rightSide='abcdefghijklmnopqrstuvwxyz0123456789&amp;_<>?!()[]{}'
        $upsidedown='ɐqɔpǝɟƃɥıɾʞʃɯuodbɹsʇnʌʍxʎz012Ɛᔭ59Ɫ86⅋‾><¿¡)(][}{'
        $output = [System.Text.StringBuilder]::New($text.Length);
        for($i = $text.Length -1; $i -ge 0; $i--)
        {
            # Get the character
            $c = $text[$i]

            # Find the index of the character in the right side up array.
            $indR = $rightSide.IndexOf([char]::ToLower($c))

            if($indR -gt 0)
            {
                $replacement = $upsidedown[$indR];
                if ([char]::IsUpper($c))
                {
                    # Try to make it upper case
                    $replacement = [char]::ToUpper($replacement);
                }

                # Stringbuilder returns a value when you append. 
                # Assigning to null to prevent.
                $null = $output.Append($replacement)
            }
            else{
                $null = $output.Append($c)
            }
        }

        return $output.ToString()
    }
}

So there was the program. All it really does, it maps right side up characters to their inverse. In the spirit of the rest of this site, here is an ugly one liner which does the same thing. Pretty much it’s just the first answer all mushed together, but it sure looks cool.

function Flip-Text2
{
    [CmdLetBinding()]
    param
    (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)][String]$text
    )
    process
    {
        ($text[($text.Length-1)..0]|%{'ɐqɔpǝɟƃɥıɾʞʃɯuodbɹsʇnʌʍxʎz012Ɛᔭ59Ɫ86⅋‾><¿¡)(][}{ '[("$(97..122|%{[char]$_})$(0..9)&amp;_<>?!()[]{}"-replace' ','').IndexOf($_)]})-join''
    }
}

This one doesn’t support any upper case characters.

Leave a Reply

Your email address will not be published. Required fields are marked *