From e8ae9d8cda18882d3fd07031879303d65504456b Mon Sep 17 00:00:00 2001 From: Nathan Anderson Date: Thu, 2 May 2024 15:40:22 -0600 Subject: [PATCH] monke --- lib/main.dart | 76 ++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 69 insertions(+), 7 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index 98245b5..4ed78f9 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -20,6 +20,49 @@ class MyApp extends StatelessWidget { } } +abstract class ListStrategy { + List compose(List items); +} + +class Monkey { + Monkey({required this.name, required this.power}); + final String name; + final int power; + + @override + String toString() => '$name - Power: $power'; +} + +class GreatestMonkeyStrategy implements ListStrategy { + @override + List compose(List items) { + return [ + items.fold( + Monkey(name: '', power: 0), (aMonkey, bMonkey) => aMonkey.power > bMonkey.power ? aMonkey : bMonkey) + ]; + } +} + +class WeakMonkeysStrategy implements ListStrategy { + @override + List compose(List items) { + return items + .where( + (element) => element.power <= 200, + ) + .toList(); + } +} + +List monkeys = [ + Monkey(name: 'Mortimer', power: 25), + Monkey(name: 'ApeMan', power: 354), + Monkey(name: 'Spider', power: 65), + Monkey(name: 'DK', power: 500), + Monkey(name: 'Tim', power: 120), + Monkey(name: 'Kong', power: 25400), +]; + class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @@ -28,6 +71,16 @@ class MyHomePage extends StatefulWidget { } class _MyHomePageState extends State { + ListStrategy listStrat = WeakMonkeysStrategy(); + + void swapStrategies() { + if (listStrat.runtimeType == WeakMonkeysStrategy) { + setState(() => listStrat = GreatestMonkeyStrategy()); + return; + } + setState(() => listStrat = WeakMonkeysStrategy()); + } + @override Widget build(BuildContext context) { return Scaffold( @@ -39,13 +92,22 @@ class _MyHomePageState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - const Text( - 'You have pushed the button this many times:', - ), - Text( - 'some text', - style: Theme.of(context).textTheme.headlineMedium, - ), + const Text('All monkeys:'), + ...monkeys + .map( + (e) => Text(e.toString()), + ) + .toList(), + const SizedBox(height: 50), + Text(listStrat.runtimeType.toString()), + ...listStrat + .compose(monkeys) + .map( + (e) => Text(e.toString()), + ) + .toList(), + const SizedBox(height: 100), + ElevatedButton(onPressed: () => swapStrategies(), child: const Text('Change Strats')), ], ), ),