• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023 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
16import { SyntaxKind } from 'typescript';
17import type { EnumEntity } from '../declaration-node/enumDeclaration';
18
19/**
20 * generate enum
21 * @param rootName
22 * @param enumDeclaration
23 * @returns
24 */
25export function generateEnumDeclaration(rootName: string, enumDeclaration: EnumEntity): string {
26  let enumBody = '';
27  if (enumDeclaration.exportModifiers.length !== 0) {
28    enumBody += `export const ${enumDeclaration.enumName} = {\n`;
29  } else {
30    enumBody += `const ${enumDeclaration.enumName} = {\n`;
31  }
32
33  let defaultValue = 0;
34  enumDeclaration.enumMembers.forEach(member => {
35    if (member.enumKind === SyntaxKind.TypeReference) {
36      enumBody += `${member.enumValueName}: new ${member.enumValue},\n`;
37    } else if (member.enumKind === SyntaxKind.NumericLiteral) {
38      defaultValue = parseInt(member.enumValue.replace(/"/g, '').replace(/'/g, ''));
39      enumBody += `${member.enumValueName}: ${defaultValue},\n`;
40      defaultValue++;
41    } else if (member.enumKind === SyntaxKind.StringLiteral) {
42      enumBody += `${member.enumValueName}: ${member.enumValue},\n`;
43    } else {
44      if (member.enumValue === '' || member.enumValue === null || member.enumValue === undefined) {
45        enumBody += `${member.enumValueName}: ${defaultValue},\n`;
46        defaultValue++;
47      } else {
48        enumBody += `${member.enumValueName}: ${member.enumValue},\n`;
49      }
50    }
51  });
52  enumBody += '}\n';
53  return enumBody;
54}
55