Skip to content

Instantly share code, notes, and snippets.

@Janiczek
Created December 3, 2023 07:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Janiczek/787f75e97cd0c00b5f74f73ce17f3e8a to your computer and use it in GitHub Desktop.
Save Janiczek/787f75e97cd0c00b5f74f73ce17f3e8a to your computer and use it in GitHub Desktop.
Synchronous string normalization in Elm
<!DOCTYPE html>
<html charset="utf-8">
<head>
</head>
<body>
<div id="elm"></div>
<script>
// THIS HAS TO HAPPEN BEFORE THE IMPORT OF elm.js
// OTHERWISE OBJECTS CREATED WITH Json.Encode.object WON'T HAVE THIS PROPERTY
Object.defineProperty(Object.prototype, 'normalizedNFC', {
get() { return this.stringToBeNormalized.normalize('NFC') }
})
Object.defineProperty(Object.prototype, 'normalizedNFD', {
get() { return this.stringToBeNormalized.normalize('NFD') }
})
Object.defineProperty(Object.prototype, 'normalizedNFKC', {
get() { return this.stringToBeNormalized.normalize('NFKC') }
})
Object.defineProperty(Object.prototype, 'normalizedNFKD', {
get() { return this.stringToBeNormalized.normalize('NFKD') }
})
</script>
<script src="elm.js"></script>
<script>
Elm.Main.init({node: document.getElementById('elm')});
</script>
</body>
</html>
module Main exposing (main)
import Html exposing (Html)
import Json.Decode
import Json.Encode
main : Html msg
main =
Html.ul []
[ viewVariant "Non-normalized" identity
, viewVariant "NFC" normalizeNFC
, viewVariant "NFD" normalizeNFD
, viewVariant "NFKC" normalizeNFKC
, viewVariant "NFKD" normalizeNFKD
]
normalizeNFC : String -> String
normalizeNFC string =
normalizeWith "NFC" string
normalizeNFD : String -> String
normalizeNFD string =
normalizeWith "NFD" string
normalizeNFKC : String -> String
normalizeNFKC string =
normalizeWith "NFKC" string
normalizeNFKD : String -> String
normalizeNFKD string =
normalizeWith "NFKD" string
inputString : String
inputString =
"ñ"
viewVariant : String -> (String -> String) -> Html msg
viewVariant label fn =
let
processed =
fn inputString
in
Html.li []
[ Html.text label
, Html.ul []
[ Html.li [] [ Html.text processed ]
, Html.li []
[ processed
|> String.length
|> String.fromInt
|> (\s -> "Length: " ++ s)
|> Html.text
]
]
]
normalizeWith : String -> String -> String
normalizeWith normalizationType string =
Json.Encode.object
[ ( "stringToBeNormalized"
, Json.Encode.string string
)
]
|> Json.Decode.decodeValue
(Json.Decode.field ("normalized" ++ normalizationType) Json.Decode.string)
|> -- Perhaps not safe to do this?
Result.withDefault string
@Carlsson87
Copy link

Carlsson87 commented Dec 3, 2023

Wait. Isn't this illegal? (😉)

@Janiczek
Copy link
Author

Janiczek commented Dec 3, 2023

@Carlsson87 Why would it be?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment