• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2022 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 { 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      enumBody += `${member.enumValueName}: ${member.enumValue.replace(/"/g, '')},\n`;
39    } else if (member.enumKind === SyntaxKind.StringLiteral) {
40      enumBody += `${member.enumValueName}: ${member.enumValue},\n`;
41    } else {
42      if (member.enumValue === '' || member.enumValue === null || member.enumValue === undefined) {
43        enumBody += `${member.enumValueName}: ${defaultValue},\n`;
44        defaultValue++;
45      } else {
46        enumBody += `${member.enumValueName}: ${member.enumValue},\n`;
47      }
48    }
49  });
50  enumBody += '}\n';
51  return enumBody;
52}
53