builtin_extensions.dart 801 B

12345678910111213141516171819202122232425262728293031323334353637
  1. extension DurationExtension on String {
  2. Duration? toDuration() {
  3. try {
  4. final parts = split(':')
  5. .map((e) => double.parse(e).toInt())
  6. .toList(growable: false);
  7. return Duration(hours: parts[0], minutes: parts[1], seconds: parts[2]);
  8. } catch (e) {
  9. return null;
  10. }
  11. }
  12. double toDouble() {
  13. return double.parse(this);
  14. }
  15. int toInt() {
  16. return int.parse(this);
  17. }
  18. }
  19. extension ListExtension<E> on List<E> {
  20. List<E> uniqueConsecutive<T>([T Function(E element)? key]) {
  21. key ??= (E e) => e as T;
  22. int i = 1, j = 1;
  23. for (; i < length; i++) {
  24. if (key(this[i]) != key(this[i - 1])) {
  25. if (i != j) {
  26. this[j] = this[i];
  27. }
  28. j++;
  29. }
  30. }
  31. length = length == 0 ? 0 : j;
  32. return this;
  33. }
  34. }