Dart: Remove from Iterable until criteria is met

65 views Asked by At

I am having an Iterable<MyClass> where MyClass has an attribute data. Now I want to remove elements from my Iterable starting from the last added item. I want to remove them until the sum of all characters in all data attributes that are still in the Iterable are below some threshold.

Of course I could just iterate over the list, remove the last, then check, remove next etc. With a simple loop and if-statement. I just wonder if there is a more elegant way to do this in dart? Using some builtin function?

Thanks!

1

There are 1 answers

1
Ildeberto Vasconcelos On

It's important to know what approach you're using now

But if I had a similar problem I would do it this way:

class MyClass { String data;

  MyClass(this.data);
}

void main() {
  Iterable<MyClass> myIterable = [
    MyClass("abc"),
    MyClass("def"),
    MyClass("ghi"),
    MyClass("jkl"),
  ];

  int threshold = 10; // Your threshold value

  // Calculate the sum of characters in all data attributes
  int sum = myIterable.map((myClass) => myClass.data.length).fold(0, (prev, length) => prev + length);

  // Remove elements from the end until the sum is below the threshold
  List<MyClass> remaining = myIterable.toList().reversed.takeWhile((myClass) {
    sum -= myClass.data.length;
    return sum >= threshold;
  }).toList();

  print(remaining); // Remaining elements after removal
}