Skip to content

Commit

Permalink
Remove usage of Maps.mapToString() (flutter#71)
Browse files Browse the repository at this point in the history
  • Loading branch information
srawlins authored and lrhn committed Feb 23, 2018
1 parent 9f081c7 commit 5943e16
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
33 changes: 32 additions & 1 deletion lib/src/canonicalized_map.dart
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,40 @@ class CanonicalizedMap<C, K, V> implements Map<K, V> {

Iterable<V> get values => _base.values.map((pair) => pair.last);

String toString() => Maps.mapToString(this);
String toString() {
// Detect toString() cycles.
if (_isToStringVisiting(this)) {
return '{...}';
}

var result = new StringBuffer();
try {
_toStringVisiting.add(this);
result.write('{');
bool first = true;
forEach((k, v) {
if (!first) {
result.write(', ');
}
first = false;
result.write('$k: $v');
});
result.write('}');
} finally {
assert(identical(_toStringVisiting.last, this));
_toStringVisiting.removeLast();
}

return result.toString();
}

bool _isValidKey(Object key) =>
(key == null || key is K) &&
(_isValidKeyFn == null || _isValidKeyFn(key));
}

/// A collection used to identify cyclic maps during toString() calls.
final List _toStringVisiting = [];

/// Check if we are currently visiting `o` in a toString() call.
bool _isToStringVisiting(o) => _toStringVisiting.any((e) => identical(o, e));
29 changes: 29 additions & 0 deletions test/canonicalized_map_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,35 @@ void main() {
});
});

group("CanonicalizedMap builds an informative string representation", () {
var map;
setUp(() {
map = new CanonicalizedMap<int, String, dynamic>(int.parse,
isValidKey: (s) => new RegExp(r"^\d+$").hasMatch(s as String));
});

test("for an empty map", () {
expect(map.toString(), equals('{}'));
});

test("for a map with one value", () {
map.addAll({"1": "value 1"});
expect(map.toString(), equals('{1: value 1}'));
});

test("for a map with multiple values", () {
map.addAll(
{"1": "value 1", "01": "value 01", "2": "value 2", "03": "value 03"});
expect(
map.toString(), equals('{01: value 01, 2: value 2, 03: value 03}'));
});

test("for a map with a loop", () {
map.addAll({"1": "value 1", "2": map});
expect(map.toString(), equals('{1: value 1, 2: {...}}'));
});
});

group("CanonicalizedMap.from", () {
test("canonicalizes its keys", () {
var map = new CanonicalizedMap.from(
Expand Down

0 comments on commit 5943e16

Please sign in to comment.