MCPcopy Create free account
hub / github.com/glideapps/quicktype / shouldBeMap

Function shouldBeMap

src/InferMaps.ts:12–54  ·  view source on GitHub ↗
(properties: Map<string, Type>)

Source from the content-addressed store, hash-verified

10const mapSizeThreshold = 20;
11
12export function shouldBeMap(properties: Map<string, Type>): [OrderedSet<Type>, boolean] | undefined {
13 // Only classes with a certain number of properties are inferred
14 // as maps.
15 if (properties.size < mapSizeThreshold) {
16 return undefined;
17 }
18
19 // We need to handle three cases for maps (and the fourth case
20 // where we leave the class as is):
21 //
22 // 1. All property types are null.
23 // 2. Some property types are null or nullable.
24 // 3. No property types are null or nullable.
25 let nonNullCases: OrderedSet<Type> | undefined = undefined;
26 let isNullable = false;
27 let canBeMap = true;
28 // Check that all the property types are the same, modulo nullability.
29 properties.forEach(t => {
30 // The set of types first property can be, minus null.
31 const nn = nonNullTypeCases(t);
32 if (!nn.isEmpty()) {
33 if (nonNullCases !== undefined) {
34 // The set of non-null cases for all other properties must
35 // be the the same, otherwise we won't infer a map.
36 if (!nn.toSet().equals(nonNullCases.toSet())) {
37 canBeMap = false;
38 return false;
39 }
40 } else {
41 nonNullCases = nn;
42 }
43 }
44 isNullable = isNullable || t.isNullable;
45 });
46 if (!canBeMap) {
47 return undefined;
48 }
49 if (nonNullCases === undefined) {
50 assert(isNullable, "Non-nullable map candidate with no types");
51 return [OrderedSet(), true];
52 }
53 return [nonNullCases, isNullable];
54}
55
56export function replaceClass(setOfOneClass: Set<ClassType>, builder: GraphRewriteBuilder<ClassType>): TypeRef {
57 const c = defined(setOfOneClass.first());

Callers 2

replaceClassFunction · 0.85
inferMapsFunction · 0.85

Calls 3

nonNullTypeCasesFunction · 0.90
assertFunction · 0.90
equalsMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…