Skip to content

Commit

Permalink
Add buildString() and .toChar() function
Browse files Browse the repository at this point in the history
  • Loading branch information
ghasemdev committed Nov 3, 2021
1 parent 4dca258 commit b5af19f
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/src/num.dart
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,8 @@ extension DoubleToBytesExtension<T extends double> on T {
return data.buffer.asUint8List();
}
}

extension IntToCharExtension<T extends int> on T {
/// Converts this [int] value to character.
String toChar() => String.fromCharCode(this);
}
8 changes: 8 additions & 0 deletions lib/src/string.dart
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,11 @@ extension NullableStringIsNotNullOrEmptyExtension on String? {
/// Returns `true` if the string is neither null nor empty.
bool get isNotNullOrEmpty => !isNullOrEmpty;
}

/// Builds new string by populating newly created [StringBuffer] using provided [builderAction]
/// and then converting it to [String].
String buildString(void Function(StringBuffer it) builderAction) {
final buffer = StringBuffer();
builderAction(buffer);
return buffer.toString();
}
6 changes: 6 additions & 0 deletions test/num_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,12 @@ void main() {
Uint8List.fromList([21, 205, 91, 7, 0, 0, 0, 0]),
);
});

test('.toChar()', () {
expect(97.toChar(), 'a');
expect(65.toChar(), 'A');
expect(37.toChar(), '%');
});
});

group('DoubleX', () {
Expand Down
13 changes: 13 additions & 0 deletions test/string_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -270,5 +270,18 @@ void main() {
expect(() => 'awesomeString'.slice(-14), throwsRangeError);
expect(() => 'awesomeString'.slice(-1, -2), throwsRangeError);
});

test('buildString()', () {
expect(buildString((it) => it.write('test')), 'test');

expect(
buildString((it) {
for (var i = 0; i < 10; i++) {
it.write(i);
}
}),
'0123456789',
);
});
});
}

0 comments on commit b5af19f

Please sign in to comment.