From d2816eaf21a807f9eb0be3599fbc800fdf248853 Mon Sep 17 00:00:00 2001 From: guilherme Date: Tue, 17 Dec 2024 21:52:37 +1030 Subject: [PATCH] fix: lookup expected months in sorted order --- lib/src/param_cleanup_rules.dart | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/lib/src/param_cleanup_rules.dart b/lib/src/param_cleanup_rules.dart index d28cd42..15f4c17 100644 --- a/lib/src/param_cleanup_rules.dart +++ b/lib/src/param_cleanup_rules.dart @@ -122,9 +122,19 @@ String _restoreMillisecons(String formattedString, String separator) { ); } +// .reversed because it works for disambiguation +// (e.g., in vi locale try 'thang 12' before 'thang 1') +Iterable _sortMonths(Iterable months) { + final sorted = months.toList() + ..sort((a, b) => a.name.length.compareTo(b.name.length)) + ..sort((a, b) => a.number.compareTo(b.number)); + + return sorted.reversed; +} + Month? _expectMonth(DateParsingParameters parameters) { final timestamp = parameters.formattedString.toLowerCase(); - final month = parameters.parserInfo.months.where( + final month = _sortMonths(parameters.parserInfo.months).where( (element) => element.name.tryToInt() == null && timestamp.contains(element.name.toLowerCase()), @@ -136,12 +146,22 @@ Month? _expectMonth(DateParsingParameters parameters) { return month.firstOrNullExtension ?? english.firstOrNullExtension; } +// .reversed because it works for disambiguation +// (e.g., in vi locale try 'thang 12' before 'thang 1') +Iterable _sortWeekdays(Iterable weekdays) { + final sorted = weekdays.toList() + ..sort((a, b) => a.name.length.compareTo(b.name.length)) + ..sort((a, b) => a.number.compareTo(b.number)); + + return sorted.reversed; +} + Weekday? _expectWeekday(DateParsingParameters parameters) { // TODO(gbassisp): allow weekday in any part of the string // currently unsupported because some locales can have a conflict between // month and weekday (e.g., "Mar" in French for Mardi and Mars) final timestamp = parameters.formattedString.toLowerCase(); - var weekday = parameters.parserInfo.weekdays + var weekday = _sortWeekdays(parameters.parserInfo.weekdays) .where( (element) => timestamp.startsWith(element.name.toLowerCase()), // (element) => timestamp