Last active
December 1, 2021 18:15
-
-
Save mahsumurebe/4fe1176c55cbc5edcf1995773c90d77a to your computer and use it in GitHub Desktop.
Map To List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'map_extension.dart'; | |
void main() { | |
Map<dynamic, dynamic> a = <dynamic, dynamic>{ | |
0: 'text', | |
'1': [1, 2, 3], | |
'2': {'a': 'b', 'c': 'd'}, | |
'3': {'0': 'a', '1': 'd'}, | |
'4': {'a': '2', '3': 'd'}, | |
'5': [ | |
1, | |
2, | |
3, | |
{'0': 'a', '1': 'd'}, | |
{ | |
'0': 'q', | |
'1': {'0': 'a', '1': 'd'} | |
} | |
], | |
}; | |
print(a); | |
print(a.toList()); | |
print(a.toList(true)); | |
print(a.toList(true, 0)); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:math'; | |
/// Inline convert method | |
_convert<T>(Map map, | |
[bool recursive = false, int depth = -1, int depthNumber = 0]) { | |
int maxKeyNumber = | |
map.keys.map<int>((e) => int.parse(e.toString(), radix: 10)).reduce(max); | |
List<T?> output = List.filled(maxKeyNumber + 1, null); | |
for (int i = 0; i < maxKeyNumber + 1; i++) { | |
dynamic value; | |
if (map.containsKey(i)) { | |
value = map[i]; | |
} else { | |
value = map[i.toString()]; | |
} | |
if (recursive && (depth == -1 || depth >= depthNumber)) { | |
if (value is List) { | |
value = value.map((e) { | |
if (e is Map) { | |
if (e.isCanList()) { | |
return _convert(e, recursive, depth, depthNumber + 1); | |
} | |
} | |
return e; | |
}); | |
} else if (value is Map && value.isCanList()) { | |
value = _convert(value, recursive, depth, depthNumber + 1); | |
} | |
} | |
output[i] = value; | |
} | |
return output; | |
} | |
/// Map Extension | |
/// | |
/// Author: Mahsum UREBE <info@mahsumurebe.com> | |
extension Case on Map { | |
/// Check is number | |
bool _isNumber(dynamic x) { | |
return x is int || (x is String && RegExp(r'^[0-9]+$', multiLine: true).hasMatch(x)); | |
} | |
/// Can it be converted to a [List]? | |
isCanList() { | |
return keys.every(_isNumber); | |
} | |
/// Convert To List | |
/// | |
/// Key values must be int or integer strings. | |
/// Otherwise, it throws [FormatException]. | |
/// | |
/// if [recursive] is true, elements are converted | |
/// to [List] recursively. If [depth] is -1. all | |
/// internal elements will be converted to List. | |
toList<T>([bool recursive = false, int depth = -1]) { | |
if (isCanList()) { | |
return _convert<T>(this, recursive, depth); | |
} | |
throw FormatException('Map cannot be converted to list'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment