Skip to content

Commit

Permalink
✅ ✨ Adds truncateMiddle extension
Browse files Browse the repository at this point in the history
  • Loading branch information
esentis committed Nov 14, 2021
1 parent ee0c753 commit 1478a92
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
30 changes: 30 additions & 0 deletions lib/string_extensions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1577,4 +1577,34 @@ extension MiscExtensions on String? {
}
return '${this!.substring(0, length)}...';
}
/// Truncates a long `String` in the middle while retaining the beginning and the end.
///
/// [maxChars] must be more than 0.
///
/// If [maxChars] > String.length the same `String` is returned without truncation.
///
/// ### Example
///
/// ```dart
/// String f = 'congratulations';
/// String truncated = f.truncateMiddle(5); // Returns 'con...ns'
String? truncateMiddle(int maxChars) {
if (this == null) {
return null;
}
if (this!.isEmpty) {
return this;
}
if (maxChars <= 0) {
return this;
}
if (maxChars > this!.length) {
return this;
}

int leftChars = (maxChars / 2).ceil();
int rightChars = maxChars - leftChars;
return '${this!.first(n: leftChars)}...${this!.last(n: rightChars)}';
}
}
13 changes: 13 additions & 0 deletions test/string_extensions_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -675,4 +675,17 @@ void main() {
expect(t1.truncate(-13), 'peanutbutter');
},
);
test(
'Truncates the string in the middle with "..." keeping start and ending the same',
() {
String t1 = 'peanutbutter';
expect(t1.truncateMiddle(3), 'pe...r');
expect(t1.truncateMiddle(0), 'peanutbutter');
expect(t1.truncateMiddle(4), 'pe...er');
expect(t1.truncateMiddle(2), 'p...r');
expect(t1.truncateMiddle(1), 'p...');
expect(t1.truncateMiddle(13), 'peanutbutter');
expect(t1.truncateMiddle(-13), 'peanutbutter');
},
);
}

0 comments on commit 1478a92

Please sign in to comment.