[毎日Kotlin] Day40. Html builder

2018.03.27

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

はじめに

毎日Kotlinシリーズです。

このシリーズを初めての方はこちらです。「毎日Kotlin」はじめました | Developers.IO

問題

Html builders | Try Kotlin

  1. Fill the table with the proper values from the product list. The products are declared in data.kt.

  2. Color the table like a chess board (using getTitleColor() and getCellColor() functions above). Pass a color as an argument to the functions tr, td.

You can run 'JavaScript(Canvas)' configuration to see the rendered table.

fun renderProductTable(): String {
    return html {
        table {
            tr {
                td {
                    text("Product")
                }
                td {
                    text("Price")
                }
                td {
                    text("Popularity")
                }
            }
            val products = getProducts()
            TODO()
        }
    }.toString()
}

fun getTitleColor() = "#b9c9fe"
fun getCellColor(row: Int, column: Int) = if ((row + column) %2 == 0) "#dce4ff" else "#eff2ff"

狙い

ここで考えて欲しい問題の意図はなんだろうか?

仕組みは明日で今日は、HTML Builderの記述を堪能しましょう。どうやって実現しているか考えてみると楽しいと思います。

解答例

fun renderProductTable(): String {
    return html {
        table {
            tr (color = getTitleColor()) {
                td {
                    text("Product")
                }
                td {
                    text("Price")
                }
                td {
                    text("Popularity")
                }
            }
            val products = getProducts()
            for ((index, product) in products.withIndex()) {
                tr {
                    td (color = getCellColor(index, 0)) {
                        text(product.description)
                    }
                    td (color = getCellColor(index, 1)) {
                        text(product.price)
                    }
                    td (color = getCellColor(index, 2)) {
                        text(product.popularity)
                    }
                }
            }
        }
    }.toString()
}

tr,tdをproducts分作れば良いので、for文かなにかで回せばOKです。 とても直感的なコードだと思いませんか?

これを実現するための技術はこれまで解いてきた問題を組み合わせることで実現できます。特にラムダ関連の問題を見直すと良いと思います。

あとがき

Day41.でまたお会いしましょう。