• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2016 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5/// Indexes a list of `enum` values by simple name.
6///
7/// In Dart enum names are prefixed with enum class name. For example, for
8/// `enum Vote { yea, nay }`, `Vote.yea.toString()` produces `"Vote.yea"`
9/// rather than just `"yea"` - the simple name. This class provides methods for
10/// getting and looking up by simple names.
11///
12/// Example:
13///
14///     enum Vote { yea, nay }
15///     final index = new EnumIndex(Vote.values);
16///     index.lookupBySimpleName('yea'); // returns Vote.yea
17///     index.toSimpleName(Vote.nay); // returns 'nay'
18class EnumIndex<E> {
19  /// Creates an index of [enumValues].
20  EnumIndex(List<E> enumValues)
21    : _nameToValue = Map<String, E>.fromIterable(
22        enumValues,
23        key: _getSimpleName,
24      ),
25      _valueToName = Map<E, String>.fromIterable(
26        enumValues,
27        value: _getSimpleName,
28      );
29
30  final Map<String, E> _nameToValue;
31  final Map<E, String> _valueToName;
32
33  /// Given a [simpleName] finds the corresponding enum value.
34  E lookupBySimpleName(String simpleName) => _nameToValue[simpleName];
35
36  /// Returns the simple name for [enumValue].
37  String toSimpleName(E enumValue) => _valueToName[enumValue];
38}
39
40String _getSimpleName(dynamic enumValue) {
41  return enumValue.toString().split('.').last;
42}
43