How is Dict.get case insensitive?

I would like to grab the Total-RecordsHTTP response key response.headers.

The problem is that in some browsers it is returned by the server Total-Records, but in another it is lowercase.

I would like to get the value of the header Total-Recordsregardless of its case. How do you do this?

+4
source share
5 answers

In the absence of a universal case-insensitive dictionary, you can hack a manual search:

caseInsensitiveGet : String -> Dict String v -> Maybe v
caseInsensitiveGet key dict =
    let
        lowerKey = String.toLower key
    in
        Dict.toList dict
            |> List.filterMap (\(k, v) ->
                if String.toLower k == lowerKey then
                    Just v
                else
                    Nothing)
            |> List.head

, , . , , , .

+3

, - - , . ,

case (Dict.get "Total-Records" response.headers, Dict.get "total-Records" response.headers) of 
    (Just s, _) -> 
         s 
    (_, Just s) ->
         s 
    _ ->
         <handle error case>

if then else.

+2

find elm-community/dict-extra :

import Dict.Extra

caseInsensitiveGet : String -> Dict String v -> Maybe v
caseInsensitiveGet key =
    let
        lowerKey = String.toLower key
    in
        Dict.Extra.find (\k _ -> String.toLower k == lowerKey)
            >> Maybe.map Tuple.second
+2

, ( elm-community/list-extra):

getFirstCaseInsensitive : String -> Dict String v -> Maybe v
getFirstCaseInsensitive key dict =
    let
        key_ =
            String.toLower key
    in
        dict
            |> Dict.toList
            |> List.Extra.find
                ((==) key_ << String.toLower << Tuple.first)
            |> Maybe.map Tuple.second
0

, Dict.Extra.mapKeys:

import Dict.Extra


headers =
       Dict.Extra.mapKeys String.toLower response.headers
0

Source: https://habr.com/ru/post/1678709/


All Articles