Created
February 17, 2024 22:01
-
-
Save kascote/2d2f82ed63407cd979ac0b1e2ac2209b to your computer and use it in GitHub Desktop.
simple array path traversal
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
/// Traverse the list by the given path. | |
/// ex: listPath<int>([1, 2, [3, 4]], '2.1') => 4 | |
T? listPath<T>(Object list, String path) { | |
if (path.isEmpty) return null; | |
var result = list; | |
for (final part in path.split('.')) { | |
if (result is! List) return null; | |
final idx = int.tryParse(part); | |
if (idx == null || idx < 0 || result.length <= idx) return null; | |
result = result[idx] as Object; | |
} | |
if (result is T) return result as T; | |
return null; | |
} | |
void main() { | |
assert(listPath<int>([], '') == null, 'error'); | |
assert(listPath<int>([1], '0') == 1, '0 error'); | |
assert(listPath<int>([1], '1') == null, '1 error'); | |
assert(listPath<int>([1], '-1') == null, '-1 error'); | |
assert(listPath<int>([], '1.1') == null, '1.1 error'); | |
assert(listPath<int>([1, 2, [3, 4]], '0') == 1, '0 error'); | |
assert(listPath<int>([1, 2, [3, 4]], '2.1') == 4, '2.1 error'); | |
assert(listPath<int>([1, 2, [3, 4]], '2.2') == null, '2.2 error'); | |
assert(listPath<int>([1, 2, [3, 4]], '2.1.1') == null, '2.1.1 error'); | |
assert(listPath<int>([], 'a') == null, 'a error'); | |
assert(listPath<int>([], 'a.b') == null, 'a.a error'); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment