🐧

【Dart入門】高階関数で「辛さレベル順に食材を並べる」アプリ風コード🍛

に公開

今回は、Dartの「高階関数」を使って、カレーの食材リストを「辛さレベル順」に並べ替え、フィルター&マッピングするサンプルコードを解説します(しません)!

  1. Ingredient(材料)クラスの定義
class Ingredient {
  final String name;
  final int spiciness; //からさレベル(1~10);

  Ingredient(this.name, this.spiciness);
}

2.高階関数 filterMapAndSortBySpiciness

List<String> filterMapAndSortBySpiciness(
  List<Ingredient> ingredients,
  bool Function(Ingredient) filter,
  String Function(Ingredient) mapper,
) {
  List<Ingredient> filtered = ingredients.where(filter).toList();

  filtered.sort((a, b) => b.spiciness.compareTo(a.spiciness));

  return filtered.map(mapper).toList();
}
  1. フィルター関数&マッパー関数
bool isSpicy(Ingredient ingredient) => ingredient.spiciness >= 5;

String decorateForCurry(Ingredient ingredient) =>
    '${ingredient.name} (辛さレベル: ${ingredient.spiciness})';

4.実行例

void main() {
  List<Ingredient> ingredients = [
    Ingredient('じゃがいも', 1),
    Ingredient('スパイスミックス', 8),
    Ingredient('鶏肉', 2),
    Ingredient('唐辛子', 10),
    Ingredient('ブラックペッパー', 6),
    Ingredient('玉ねぎ', 1),
  ];

  List<String> spicyIngredients = filterMapAndSortBySpiciness(
    ingredients,
    isSpicy,
    decorateForCurry,
  );

  print(spicyIngredients);
}
実行結果
[唐辛子 (辛さレベル: 10), スパイスミックス (辛さレベル: 8), ブラックペッパー (辛さレベル: 6)]

ps.メモ書きです

Discussion