Open rekire opened 7 months ago
Did you try const {'Monday', 'Sunday'}.contains(weekday)
? It should be more performant.
main() {
var weekday = 'Monday';
print(const {'Monday', 'Tuesday'}.contains(weekday)); // true
weekday = 'Sunday';
print(const {'Monday', 'Tuesday'}.contains(weekday)); // false
}
You may want to move this request to the dart-lang/sdk repository.
I'd probably use the constant set too, if the values can be constant, at least unless performance is very, very important, and I know something that can make the check more efficient than a hash set lookup (or a linear v == c1 || v == c2 || ...
check).
I'd definitely not create a list, or even a set, for every call and then do a contains
on that. Doing linear work to set up an efficient one-use contains
is strictly worse than just v == v1 || v == v2 || ... || v == vn
.
A more direct approach could be:
extension AnyOf on Object {
bool anyOf(Object v1, Object v2,
[Object? v3,
Object? v4,
Object? v5,
Object? v6,
Object? v7,
Object? v8,
Object? v9,
Object? v10]) {
return this == v1 ||
this == v2 ||
this == v3 ||
v3 != null &&
(this == v4 ||
v4 != null &&
(this == v5 ||
v5 != null &&
(this == v6 ||
v6 != null &&
(this == v7 ||
v7 != null &&
(this == v8 ||
v8 != null &&
(this == v9 ||
v9 != null &&
(this == v10)))))));
}
}
I enjoy the performance improvement and the code may look more idiomatic. Reusing the code should be simple too. For example: by creating an isWeekend
function. The major problem would be polluting the Object namespace I guess.
I have often the problem that I want to check if a value is one of a very limited list of options. In the past I wrote a extension function with a list of arguments which worked fine for me but was somehow award that this required a list. Now I found randomly a trick in
Object.hash(...)
which makes it almost perfect. Here is my suggestion for an extension which should be part of dart out of my view:Usage sample:
I'm curious what you think about it.