Skip to content

Commit

Permalink
fix: Throw ArgumentError if not flat
Browse files Browse the repository at this point in the history
  • Loading branch information
danilofuchs committed Nov 7, 2023
1 parent c63ccb9 commit bbf4838
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/src/flatten.dart
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,4 @@ Map<String, dynamic> flatten(
}

Map<String, T> _listToMap<T>(List<T> list) =>
list.asMap().map((key, value) => MapEntry(key.toString(), value));
list.asMap().map((key, value) => MapEntry(key.toString(), value));
13 changes: 13 additions & 0 deletions lib/src/unflatten.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,25 @@
/// If no [delimiter] is specified, will separate depth levels by `.`.
///
/// Unflattens arrays given that the keys are integers.
///
/// Throws [ArgumentError] if any key is already a Map or List.
///
/// Throws [ArgumentError] if there are conflicting keys.
Map<String, dynamic> unflatten(
Map<String, dynamic> flatMap, {
String delimiter = ".",
}) {
final Map<String, dynamic> result = {};

flatMap.forEach((key, value) {
if (value is Map) {
throw ArgumentError('Expected flat map, but key "$key" is a Map');
}
if (value is List) {
throw ArgumentError('Expected flat map, but key "$key" is a List');
}
});

flatMap.forEach((key, value) {
final keys = key.split(delimiter);
dynamic current = result;
Expand Down
20 changes: 19 additions & 1 deletion test/unflatten_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ void main() {
expect(result, expected);
});

test('Fails on multiple Keys', () {
test('Fails on repeated key', () {
const obj = {
'hello.lorem.ipsum': 'again',
'hello.lorem.dolor': 'sit',
Expand All @@ -69,6 +69,24 @@ void main() {
expect(() => unflatten(obj), throwsArgumentError);
});

test('Fails on nested Map', () {
const obj = {
'world': {'greet': 'hello'},
};

expect(() => unflatten(obj), throwsArgumentError);
});

test('Fails on nested nested Map', () {
const obj = {
'hello.lorem.ipsum': {
'world': {'greet': 'hello'},
},
};

expect(() => unflatten(obj), throwsArgumentError);
});

test('Custom Delimiter', () {
const obj = {
'hello world again': 'good morning',
Expand Down

0 comments on commit bbf4838

Please sign in to comment.