Splitting a list and rendering it differently

I have a list of numbers to display. I want to display all the numbers in one font colour and highlight only one (either the last one or third from the last) depending upon inter boolean.
How can this be improved?

renderDiff : List Int -> Bool -> Html msg
renderDiff lst inter =
    let
        highIndex =
            if inter then
                0

            else
                2

        firstPart =
            List.take (List.length lst - 3) lst
                |> List.map (\v -> span [] [ text (String.fromInt v ++ ", ") ])

        lastThree =
            List.drop (List.length lst - 3) lst
                |> List.indexedMap
                    (\i v ->
                        span [ classList [ ( "highlightNum", i == highIndex ) ] ]
                            [ text (String.fromInt v ++ ", ") ]
                    )
    in
    firstPart
        ++ lastThree
        |> ul []

I think this will work:

renderDiff : List Int -> Bool -> Html msg 
renderDiff lst inter = 
    let 
        offset = if inter then 3 else 1
        highIndex = (List.length lst) - offset
        items = lst 
            |> List.indexedMap 
                (\i v -> span [ classList [ ( "highlightNum", i == highIndex ) ] ] 
                    [ text (String.fromInt v ++ ", ") ] ) 
    in 
        ul [] items

(edited to fix definition of offset)

1 Like

@Titus_Anderson Actually that’s exactly how I had it in the first place. But felt why indexmap over an entire list (sometimes having more than 10,000 elements) just to highlight one item, and wanted to know if there was a more efficient way.

Also, is there a more idiomatic way of joining two lists and stuffing it into an ul?

In this particular case, I don’t think indexedMap is going to have much of a performance difference than the solution you proposed – the only difference is a boolean comparison which adds a class if true. Granted, I can see cases where an indexedMap would have significant performance implications, but this isn’t it; in those cases, though, your solution would be sufficient to reduce those concerns.

That said, even in the cases of using indexedMap that has a heavy computation in certain cases, as long as there’s some low computational way to determine the light versus heavy computational situations (via an if expression), I still think indexedMap would be a better option than map.

Regarding combining lists and adding them to a ul (or any other HTML element), I would likely use the same method you did.

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.