Skip to content

[gis_web] Make maybeEnum more robust #9093

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

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,27 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/// Attempts to retrieve an enum value from [haystack] if [needle] is not null.

/// Attempts to retrieve the enum value from [haystack] whose name matches [needle], or returns `null` if not found.
///
/// This is a safe utility method that performs a reverse lookup on an enum
/// by comparing the string [needle] with each value’s [Enum.name].
///
/// Example:
/// ```dart
/// enum AuthMethod { google, facebook, apple }
///
/// final result = maybeEnum('google', AuthMethod.values); // AuthMethod.google
/// final invalid = maybeEnum('github', AuthMethod.values); // null
/// ```
T? maybeEnum<T extends Enum>(String? needle, List<T> haystack) {
if (needle == null) {
return null;
if (needle == null) return null;
for (final T value in haystack) {
if (value.name == needle) {
return value;
}
}
return haystack.byName(needle);
return null;
}

/// The type of several functions from the library, that don't receive
Expand Down
20 changes: 20 additions & 0 deletions packages/google_identity_services_web/test/maybe_enum_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import 'package:google_identity_services_web/src/js_interop/shared.dart';
import 'package:test/test.dart';

enum AuthMethod { google, facebook, apple }

void main() {
group('maybeEnum', () {
test('returns correct enum when match is found', () {
expect(maybeEnum('google', AuthMethod.values), AuthMethod.google);
});

test('returns null when needle is null', () {
expect(maybeEnum(null, AuthMethod.values), isNull);
});

test('returns null when needle does not match', () {
expect(maybeEnum('github', AuthMethod.values), isNull);
});
});
}