Skip to content

Commit

Permalink
Add normalizeUrl, rTrim and Enum extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
petrnymsa committed Apr 19, 2024
1 parent 0a84258 commit 9138627
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
24 changes: 24 additions & 0 deletions packages/netglade_utils/lib/src/extensions/enum_extensions.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
extension EnumExtensions<T extends Enum> on Iterable<T> {
/// Finds the enum value in this list with name [name].
///
/// Goes through this collection looking for an enum with
/// name [name], as reported by [EnumName.name].
/// Returns the first value with the given name. Such a value must be found.
T byNameOrDefault(String name, {required T defaultValue}) {
try {
return byName(name);
// ignore: avoid_catching_errors, byName throws it
} on ArgumentError catch (_) {
return defaultValue;
}
}

T? byNameOrNull(String name) {
try {
return byName(name);
// ignore: avoid_catching_errors, byName throws it
} on ArgumentError catch (_) {
return null;
}
}
}
1 change: 1 addition & 0 deletions packages/netglade_utils/lib/src/extensions/extensions.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export 'date_time_extensions.dart';
export 'enum_extensions.dart';
export 'future_extensions.dart';
export 'iterable_extensions.dart';
export 'object_extensions.dart';
Expand Down
19 changes: 19 additions & 0 deletions packages/netglade_utils/lib/src/extensions/string_extensions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,25 @@ extension StringExtensions on String {
String? ifBlank([String? defaultValue]) {
return isBlank ? defaultValue : this;
}

/// Normalize supposedly string containing URL
///
/// Appends https:// when does not start with.
/// Trims any trailing '/' chars.
String normalizeUrl() {
final value = trim();

if (value.startsWith(RegExp(r'http[s]?:\/\/'))) return value.rtrim('/');

return 'https://$value'.rtrim('/');
}

/// Removes any trailing char from [chars].
String rtrim(String chars) {
final pattern = RegExp('[$chars]+\$');

return replaceAll(pattern, '');
}
}

extension NullableStringExtensions on String? {
Expand Down

0 comments on commit 9138627

Please sign in to comment.