feat(core): Add a list constructor to TypedMap

This commit is contained in:
PapaTutuWawa 2023-06-07 14:13:46 +02:00
parent f0538b0447
commit cbd90b1163
2 changed files with 22 additions and 0 deletions

View File

@ -1,5 +1,15 @@
/// A map, similar to Map, but always uses the type of the value as the key.
class TypedMap<B> {
/// Create an empty typed map.
TypedMap();
/// Create a typed map from a list of values.
TypedMap.fromList(List<B> items) {
for (final item in items) {
_data[item.runtimeType] = item;
}
}
/// The internal mapping of type -> data
final Map<Object, B> _data = {};

View File

@ -24,4 +24,16 @@ void main() {
expect(map.get<TestType1>()?.i, 1);
expect(map.get<TestType2>()?.j, false);
});
test('Test storing data in the type map using a list', () {
// Set
final map = TypedMap<BaseType>.fromList([
const TestType1(1),
const TestType2(false),
]);
// And access
expect(map.get<TestType1>()?.i, 1);
expect(map.get<TestType2>()?.j, false);
});
}