normalize method

List<MoneyTransaction> normalize({
  1. required Currency currency,
  2. List<ExchangeRate>? exchangeRates,
})

Normalizes all values to the same currency. For this, exchangeRates list must contain all the exchange rates necessary for conversions. If even one of these is missing, throws a FormatException.

The result list is sorted.

Implementation

List<MoneyTransaction> normalize({
  required Currency currency,
  List<ExchangeRate>? exchangeRates,
}) {
  final List<MoneyTransaction> normalized = [];

  if (exchangeRates != null && exchangeRates.isNotEmpty) {
    for (final MoneyTransaction transaction in this) {
      if (transaction.value.currency == currency) {
        normalized.add(transaction);
      } else {
        final ExchangeRate? rate = exchangeRates.getExchangeRate(
          from: transaction.value.currency,
          to: currency,
        );

        if (rate == null) {
          throw const FormatException(
              'exchangeRates list does not contain the exchange rate to carry'
              ' out the conversion.');
        }

        normalized.add(
          transaction.copyWith(
            value: Money(
              amount: transaction.value.convert(rate: rate).amount,
              currency: currency,
            ),
          ),
        );
      }
    }
  } else {
    for (final MoneyTransaction transaction in this) {
      if (transaction.value.currency == currency) {
        normalized.add(transaction);
      } else {
        throw const FormatException(
            'exchangeRates list does not contain the exchange rate to carry'
            ' out the conversion.');
      }
    }
  }

  normalized.sort();

  return normalized;
}