Skip to content

Instantly share code, notes, and snippets.

@kascote
Created February 17, 2024 22:01
Show Gist options
  • Save kascote/2d2f82ed63407cd979ac0b1e2ac2209b to your computer and use it in GitHub Desktop.
Save kascote/2d2f82ed63407cd979ac0b1e2ac2209b to your computer and use it in GitHub Desktop.
simple array path traversal
/// 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