@@ -11,18 +11,45 @@ var divElement = document.createElement("div")
1111divElement. innerText = . string( " Count \( count) " )
1212_ = document. body. appendChild ( divElement)
1313
14- var buttonElement = document. createElement ( " button " )
15- buttonElement . innerText = " Click me "
16- buttonElement . onclick = JSValue . object (
14+ var clickMeElement = document. createElement ( " button " )
15+ clickMeElement . innerText = " Click me "
16+ clickMeElement . onclick = JSValue . object (
1717 JSClosure { _ in
1818 count += 1
1919 divElement. innerText = . string( " Count \( count) " )
2020 return . undefined
2121 }
2222)
23+ _ = document. body. appendChild ( clickMeElement)
2324
24- _ = document. body. appendChild ( buttonElement)
25+ var encodeResultElement = document. createElement ( " pre " )
26+ var textInputElement = document. createElement ( " input " )
27+ textInputElement. type = " text "
28+ textInputElement. placeholder = " Enter text to encode to UTF-8 "
29+ textInputElement. oninput = JSValue . object (
30+ JSClosure { _ in
31+ let textEncoder = JSObject . global. TextEncoder. function!. new ( )
32+ let encode = textEncoder. encode. function!
33+ let encodedData = JSTypedArray < UInt8 > ( unsafelyWrapping: encode ( this: textEncoder, textInputElement. value) . object!)
34+ encodeResultElement. innerText = . string( encodedData. withUnsafeBytes { bytes in
35+ bytes. map { hex ( $0) } . joined ( separator: " " )
36+ } )
37+ return . undefined
38+ }
39+ )
40+ let encoderContainer = document. createElement ( " div " )
41+ _ = encoderContainer. appendChild ( textInputElement)
42+ _ = encoderContainer. appendChild ( encodeResultElement)
43+ _ = document. body. appendChild ( encoderContainer)
2544
2645func print( _ message: String ) {
2746 _ = JSObject . global. console. log ( message)
2847}
48+
49+ func hex( _ value: UInt8 ) -> String {
50+ var result = " 0x "
51+ let hexChars : [ Character ] = [ " 0 " , " 1 " , " 2 " , " 3 " , " 4 " , " 5 " , " 6 " , " 7 " , " 8 " , " 9 " , " A " , " B " , " C " , " D " , " E " , " F " ]
52+ result. append ( hexChars [ Int ( value / 16 ) ] )
53+ result. append ( hexChars [ Int ( value % 16 ) ] )
54+ return result
55+ }
0 commit comments