Skip to content

Commit

Permalink
refactor(model): ♻️ rewrite parser using a chain of responsibility pa…
Browse files Browse the repository at this point in the history
…ttern

Signed-off-by: Albert Mañosa <albertmasa2@gmail.com>
  • Loading branch information
albertms10 committed Nov 3, 2024
1 parent 7e4c66e commit cada184
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions lib/src/model/definition_entry_sense.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ import 'gender.dart';
import 'scope.dart';
import 'word.dart';

class ChainItem<T> {
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;
Expand Down Expand Up @@ -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<Scope>(function: Scope.parse, transform: scopes.add),
ChainItem(value: () => redirectWord, function: parseRedirectEntry),
ChainItem<String>(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;
Expand Down

0 comments on commit cada184

Please sign in to comment.