1/*
2 * Copyright (c) 2023-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16enum Color { Red, Green, Blue }
17
18class ColorEnumDelegate {
19  private static values_: Color[] = [Color.Red, Color.Green, Color.Blue];
20  private static names_: String[] = ["Red", "Green", "Blue"];
21
22  public static values(): Color[] { return ColorEnumDelegate.values_; }
23
24  public static ordinal(x: Color): int { return x as int; }
25
26  public static toString(x: Color): String { return ColorEnumDelegate.names_[x as int]; }
27
28  public static valueOf(name: String): Color {
29    for (let i = 0; i < ColorEnumDelegate.values_.length; i++) {
30      if (ColorEnumDelegate.names_[i] == name) { return ColorEnumDelegate.values_[i]; }
31    }
32
33    assert false : "No enum constant Color";
34    return Color.Red;
35  }
36
37  public static valueOf(ordinal: int): Color {
38    if (0 <= ordinal && ordinal < ColorEnumDelegate.values_.length) {
39      return ColorEnumDelegate.values_[ordinal];
40    }
41
42    assert false : "No enum constant Color";
43    return Color.Red;
44  }
45}
46
47function main(): void {
48  let red: Color = Color.Red;
49  assert ColorEnumDelegate.toString(red) == "Red";
50
51  assert ColorEnumDelegate.ordinal(red) == 0;
52  assert ColorEnumDelegate.ordinal(Color.Green) == 1;
53
54  assert ColorEnumDelegate.valueOf(2) == Color.Blue;
55  assert ColorEnumDelegate.valueOf(ColorEnumDelegate.ordinal(Color.Red)) == red;
56
57  assert ColorEnumDelegate.valueOf("Green") == Color.Green;
58  assert ColorEnumDelegate.valueOf(ColorEnumDelegate.toString(Color.Blue)) == Color.Blue;
59}
60