Sobes.tech
Junior

Describe the solution to the second task (processing orders via Stream API with grouping by currency and sorting by max-min difference).

sobes.tech AI

Answer from AI

To solve the task of processing orders through Stream API with grouping by currency and sorting by the difference between max and min, you can use the following approach in Dart (Flutter):

  1. There is a stream of orders (Stream<Order>), where each order contains an amount and a currency.
  2. Group the orders by currency, collecting amounts into lists.
  3. For each group, calculate the difference between the maximum and minimum amount.
  4. Sort the groups by this difference.

Example code:

class Order {
  final String currency;
  final double amount;
  Order(this.currency, this.amount);
}

void processOrders(Stream<Order> orders) async {
  final Map<String, List<double>> grouped = {};

  await for (var order in orders) {
    grouped.putIfAbsent(order.currency, () => []).add(order.amount);
  }

  final sortedCurrencies = grouped.entries.toList()
    ..sort((a, b) {
      double diffA = a.value.reduce((v, e) => v > e ? v : e) - a.value.reduce((v, e) => v < e ? v : e);
      double diffB = b.value.reduce((v, e) => v > e ? v : e) - b.value.reduce((v, e) => v < e ? v : e);
      return diffB.compareTo(diffA); // sort in descending order
    });

  for (var entry in sortedCurrencies) {
    print('Currency: \\${entry.key}, Difference: \\${entry.value.reduce((v, e) => v > e ? v : e) - entry.value.reduce((v, e) => v < e ? v : e)}');
  }
}

This code reads a stream of orders, groups them by currency, calculates the difference between the maximum and minimum amount in each group, and outputs the currencies sorted by this difference.

Describe the solution to the second task (processing… - sobes.tech