Skip to content

Commit f464644

Browse files
committed
Memoize
1 parent 97256f0 commit f464644

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/jsutils/memoize1.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* Memoizes the provided single-argument function.
3+
*/
4+
export function memoize1<A1 extends object, R>(
5+
fn: (a1: A1) => R,
6+
): (a1: A1) => R {
7+
let cache0: WeakMap<A1, R>;
8+
9+
return function memoized(a1) {
10+
if (cache0 === undefined) {
11+
cache0 = new WeakMap();
12+
}
13+
14+
let fnResult = cache0.get(a1);
15+
if (fnResult === undefined) {
16+
fnResult = fn(a1);
17+
cache0.set(a1, fnResult);
18+
}
19+
20+
return fnResult;
21+
};
22+
}

src/type/introspection.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { inspect } from '../jsutils/inspect';
22
import { invariant } from '../jsutils/invariant';
3+
import { memoize1 } from '../jsutils/memoize1';
34

45
import { DirectiveLocation } from '../language/directiveLocation';
56
import { print } from '../language/printer';
@@ -381,7 +382,6 @@ export const __Field: GraphQLObjectType = new GraphQLObjectType({
381382
if (includeSemanticNonNull) {
382383
return field.type;
383384
}
384-
// TODO: memoize
385385
return stripSemanticNonNullTypes(field.type);
386386
},
387387
},
@@ -396,8 +396,10 @@ export const __Field: GraphQLObjectType = new GraphQLObjectType({
396396
} as GraphQLFieldConfigMap<GraphQLField<unknown, unknown>, unknown>),
397397
});
398398

399-
// TODO: move this elsewhere, rename, memoize
400-
function stripSemanticNonNullTypes(type: GraphQLOutputType): GraphQLOutputType {
399+
const stripSemanticNonNullTypes = memoize1(_stripSemanticNonNullTypes);
400+
function _stripSemanticNonNullTypes(
401+
type: GraphQLOutputType,
402+
): GraphQLOutputType {
401403
if (isNonNullType(type)) {
402404
const convertedInner = stripSemanticNonNullTypes(type.ofType);
403405
if (convertedInner === type.ofType) {

0 commit comments

Comments
 (0)