-
Notifications
You must be signed in to change notification settings - Fork 88
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
lastOrNull is suboptimal #260
Comments
It's definitely a trade-off. I'm trying to add a A solution could be to do: class _Sentinel {
const _Sentinel();
}
Never _throwSentinel() => throw const _Sentinel();
bool _kTrue(_) => true;
/// ...
T? get lastOrNull {
try {
return lastWhere(_kTrue, orElse: _throwSentinel);
} on _Sentinel {
return null;
}
} That uses exceptions for control flow, but it also allows the iterable to be efficient about finding its last element. try {
return last;
} on StateError {
return null;
} but we can't know for sure that the The primitives are just not available to both allow the iterable to do an efficient The choice here was that So, tradeoffs. |
I see. I guess we could look at the type (e.g., have a different algorithm for |
The version I'm hoping to add to the platform libraries relies on It might still be worth having a separate extension for (Another approach is to have extensions extension <T> on Iterable<T> {
Iterable<T>? get emptyAsNull => this.isEmpty ? null : this;
}
extension <T> on Iterable<T>? {
Iterable<T> get nullAsEmpty => this ?? Iterable<T>.empty();
}
// Maybe similar for List/Set/String. Then instead of iterable.emptyAsNull?.last Doesn't change anything, it's still the same code that we have in this package now, it's just split into two |
I believe the current implementation produces two iterators: one for
isEmpty
and one forlast
:Unless I'm missing something here, I think this is suboptimal, especially when using this on a lazy
Iterable
(for example,giantList.where(someCondition)
.The text was updated successfully, but these errors were encountered: