elegant 2.0.3
elegant: ^2.0.3 copied to clipboard
A small collection of utility functions and classes, including a sealed Result type, iterable helpers, etc.
import 'dart:async';
import 'package:elegant/elegant.dart';
// This is a utility library, here's an example with some misc stuff in it.
Result<int, String> parsePort(String raw) {
final port = int.tryParse(raw);
if (port == null || port < 1 || port > 65535) {
return .error('Invalid port: $raw');
}
return .ok(port);
}
Future<void> main() async {
// Result<T, E> with pattern matching and combinators
final doubled = parsePort('8080').map((port) => port * 2);
final message = switch (doubled) {
Ok(:final value) => 'Port x2 = $value',
Err(:final error) => 'Failed: $error',
};
print(message);
// Collecting an Iterable<Result<T, E>>
final ports = ['80', '443', '8080'].map(parsePort).sequence();
print('Parsed ports: ${ports.unwrap()}');
// Iterable & List utilities
final diffs = [10, 15, 23].pairs((a, b) => b - a).toList();
print('Differences: $diffs');
final grouped = ['ant', 'ape', 'bat', 'cat'].mapBy((word) => word[0]);
print('By first letter: $grouped');
final cycled = ['a', 'b', 'c'].circular().take(5).toList();
print('Circular: $cycled');
// Safe cast extension
const Object maybeText = 'hello';
print('Uppercase: ${maybeText.asType<String>()?.toUpperCase()}');
// Stream aggregation
final aggregate = AggregateStreamController<String>();
final sub = aggregate.stream.listen(print);
aggregate.add(Stream.value('from stream A'), 'a');
aggregate.add(Stream.value('from stream B'), 'b');
await Future<void>.delayed(.zero);
await sub.cancel();
await aggregate.close();
}