From cada1846cee21e0a5701bf8c9ccdfff303683390 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Albert=20Ma=C3=B1osa?= Date: Mon, 4 Nov 2024 00:45:09 +0100 Subject: [PATCH] =?UTF-8?q?refactor(model):=20=E2=99=BB=EF=B8=8F=20rewrite?= =?UTF-8?q?=20parser=20using=20a=20chain=20of=20responsibility=20pattern?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Albert MaƱosa --- lib/src/model/definition_entry_sense.dart | 34 +++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/lib/src/model/definition_entry_sense.dart b/lib/src/model/definition_entry_sense.dart index d8ee3ac..c617a9f 100644 --- a/lib/src/model/definition_entry_sense.dart +++ b/lib/src/model/definition_entry_sense.dart @@ -5,6 +5,15 @@ import 'gender.dart'; import 'scope.dart'; import 'word.dart'; +class ChainItem { + final T? Function()? value; + final T Function(T)? set; + final T? Function(Element)? function; + final void Function(T)? transform; + + const ChainItem({this.value, this.set, this.function, this.transform}); +} + @immutable final class DefinitionEntrySense { final int? number; @@ -105,7 +114,32 @@ final class DefinitionEntrySense { (definition, locution) = parseDefinitionAndLocution(element); } + final chain = [ + ChainItem( + value: () => number, + set: (dynamic newNumber) => number = newNumber as int, + function: parseNumber, + ), + ChainItem( + value: () => subNumber, + set: (dynamic newSubNumber) => number = newSubNumber as int, + function: parseSubNumber, + ), + ChainItem(function: Scope.parse, transform: scopes.add), + ChainItem(value: () => redirectWord, function: parseRedirectEntry), + ChainItem(function: parseExample, transform: examples.add), + ]; + for (final child in element.children) { + for (final chainElement in chain) { + if (chainElement.value?.call() != null) continue; + final value = chainElement.function?.call(child); + if (value != null) { + final newElement = chainElement.set?.call(value); + if (newElement != null) continue; + } + } + if (number == null) { number = parseNumber(child); if (number != null) continue;