Skip to content

Commit 9138627

Browse files
committed
Add normalizeUrl, rTrim and Enum extensions
1 parent 0a84258 commit 9138627

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
extension EnumExtensions<T extends Enum> on Iterable<T> {
2+
/// Finds the enum value in this list with name [name].
3+
///
4+
/// Goes through this collection looking for an enum with
5+
/// name [name], as reported by [EnumName.name].
6+
/// Returns the first value with the given name. Such a value must be found.
7+
T byNameOrDefault(String name, {required T defaultValue}) {
8+
try {
9+
return byName(name);
10+
// ignore: avoid_catching_errors, byName throws it
11+
} on ArgumentError catch (_) {
12+
return defaultValue;
13+
}
14+
}
15+
16+
T? byNameOrNull(String name) {
17+
try {
18+
return byName(name);
19+
// ignore: avoid_catching_errors, byName throws it
20+
} on ArgumentError catch (_) {
21+
return null;
22+
}
23+
}
24+
}

packages/netglade_utils/lib/src/extensions/extensions.dart

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export 'date_time_extensions.dart';
2+
export 'enum_extensions.dart';
23
export 'future_extensions.dart';
34
export 'iterable_extensions.dart';
45
export 'object_extensions.dart';

packages/netglade_utils/lib/src/extensions/string_extensions.dart

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,25 @@ extension StringExtensions on String {
3232
String? ifBlank([String? defaultValue]) {
3333
return isBlank ? defaultValue : this;
3434
}
35+
36+
/// Normalize supposedly string containing URL
37+
///
38+
/// Appends https:// when does not start with.
39+
/// Trims any trailing '/' chars.
40+
String normalizeUrl() {
41+
final value = trim();
42+
43+
if (value.startsWith(RegExp(r'http[s]?:\/\/'))) return value.rtrim('/');
44+
45+
return 'https://$value'.rtrim('/');
46+
}
47+
48+
/// Removes any trailing char from [chars].
49+
String rtrim(String chars) {
50+
final pattern = RegExp('[$chars]+\$');
51+
52+
return replaceAll(pattern, '');
53+
}
3554
}
3655

3756
extension NullableStringExtensions on String? {

0 commit comments

Comments
 (0)