removeTypeDuplicates.js 1.72 KB
Newer Older
Rosanny Sihombing's avatar
Rosanny Sihombing committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = removeTypeDuplicates;

var _generated = require("../../validators/generated");

function getQualifiedName(node) {
  return (0, _generated.isIdentifier)(node) ? node.name : `${node.id.name}.${getQualifiedName(node.qualification)}`;
}

function removeTypeDuplicates(nodes) {
15
16
  const generics = {};
  const bases = {};
Rosanny Sihombing's avatar
Rosanny Sihombing committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  const typeGroups = new Set();
  const types = [];

  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i];
    if (!node) continue;

    if (types.indexOf(node) >= 0) {
      continue;
    }

    if ((0, _generated.isAnyTypeAnnotation)(node)) {
      return [node];
    }

    if ((0, _generated.isFlowBaseAnnotation)(node)) {
33
      bases[node.type] = node;
Rosanny Sihombing's avatar
Rosanny Sihombing committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
      continue;
    }

    if ((0, _generated.isUnionTypeAnnotation)(node)) {
      if (!typeGroups.has(node.types)) {
        nodes = nodes.concat(node.types);
        typeGroups.add(node.types);
      }

      continue;
    }

    if ((0, _generated.isGenericTypeAnnotation)(node)) {
      const name = getQualifiedName(node.id);

49
50
      if (generics[name]) {
        let existing = generics[name];
Rosanny Sihombing's avatar
Rosanny Sihombing committed
51
52
53
54
55
56
57
58
59

        if (existing.typeParameters) {
          if (node.typeParameters) {
            existing.typeParameters.params = removeTypeDuplicates(existing.typeParameters.params.concat(node.typeParameters.params));
          }
        } else {
          existing = node.typeParameters;
        }
      } else {
60
        generics[name] = node;
Rosanny Sihombing's avatar
Rosanny Sihombing committed
61
62
63
64
65
66
67
68
      }

      continue;
    }

    types.push(node);
  }

69
70
  for (const type of Object.keys(bases)) {
    types.push(bases[type]);
Rosanny Sihombing's avatar
Rosanny Sihombing committed
71
72
  }

73
74
  for (const name of Object.keys(generics)) {
    types.push(generics[name]);
Rosanny Sihombing's avatar
Rosanny Sihombing committed
75
76
77
78
  }

  return types;
}