A quick and easy way to generate WTF code is to find some deceptively simple problem that’s been well solved, and reimplement a naive solution to the problem.
Ryan found this attempt to handle HTML encoding of key characters. This code is VB.NET, which is important to keep in mind, since the Framework provides a variety of methods to do this correctly.
Function HTMLEncode(ByVal Text As String) As String
Dim i As Short
Dim acode As Short
Dim repl As String
HTMLEncode = Text
For i = Len(HTMLEncode) To 1 Step -1
acode = Asc(Mid(HTMLEncode, i, 1))
Select Case acode
Case 32
repl = " "
Case 34
repl = """
Case 38
repl = "&"
Case 60
repl = "<"
Case 62
repl = ">"
Case 32 To 127
' do not consider alphanumeric chars
Case Else
repl = "&#" & CStr(acode) & ";"
End Select
If Len(repl) Then
HTMLEncode = Left(HTMLEncode, i - 1) & repl & Mid(HTMLEncode, i + 1)
repl = ""
End If
Next
End Function
This has a little bit of everything ugly, including the old style VB returns (for those not so “blessed”, VB lets you return values from a function by simply treating the function name as a variable).
The use of Asc
to get the integer representation of the character is a subtle bug. The function is deprecated, and not going to return an ASCII code point, but whatever code page is configured for the system. There are cases where SomeChar <> Chr(Asc(SomeChar))
(example);
But this is simply an ugly and lazy HTML encoding function. To really ascend to full WTF, we need to see how they decode it.
Function HTMLDecode(ByVal html As String) As String
Dim i As Integer
HTMLDecode = html
Do
' search the next ampersand, exit if no more
i = InStr(i + 1, HTMLDecode, "&")
If i = 0 Then Exit Do
If StrComp(Mid(HTMLDecode, i, 6), " ", CompareMethod.Text) = 0 Then
HTMLDecode = Left(HTMLDecode, i - 1) & " " & Mid(HTMLDecode, i + 6)
ElseIf StrComp(Mid(HTMLDecode, i, 6), """, CompareMethod.Text) = 0 Then
HTMLDecode = Left(HTMLDecode, i - 1) & """" & Mid(HTMLDecode, i + 6)
ElseIf StrComp(Mid(HTMLDecode, i, 5), "&", CompareMethod.Text) = 0 Then
HTMLDecode = Left(HTMLDecode, i - 1) & "&" & Mid(HTMLDecode, i + 5)
ElseIf StrComp(Mid(HTMLDecode, i, 4), "<", CompareMethod.Text) = 0 Then
HTMLDecode = Left(HTMLDecode, i - 1) & "<" & Mid(HTMLDecode, i + 4)
ElseIf StrComp(Mid(HTMLDecode, i, 4), ">", CompareMethod.Text) = 0 Then
HTMLDecode = Left(HTMLDecode, i - 1) & ">" & Mid(HTMLDecode, i + 4)
End If
Loop
End Function
The true beauty of this function pair is that they aren’t reversible. A carriage return in the string would be rendered as
. When you decode the string, it stays
. The same problem arises for “smart quotes”, various dashes, or certain currency symbols- all things that might appear if someone copy/pastes from a word-processor.