Fix @memoize and make it more efficient

This commit is contained in:
Sam Vervaeck 2020-05-23 23:08:24 +02:00
parent aa1893918b
commit 9415f7a2e7
2 changed files with 22 additions and 19 deletions

View file

@ -142,7 +142,6 @@ export class TypeChecker {
node: arg,
});
}
}
}
@ -159,7 +158,7 @@ export class TypeChecker {
return this.getTypeOfNode(sym.declarations[0]);
}
@memoize
@memoize(node => node.id)
private getTypeOfNode(node: BoltSyntax): Type {
switch (node.kind) {
case SyntaxKind.BoltReferenceTypeExpression:
@ -193,8 +192,8 @@ export class TypeChecker {
type = this.resolveType('String', node)!;
} else if (typeof node.value === 'boolean') {
type = this.resolveType('bool', node)!;
} else if (typeof node.value === 'number') {
type = this.resolveType('int32', node)!;
} else if (typeof node.value === 'bigint') {
type = this.resolveType('i32', node)!;
} else {
throw new Error(`Could not derive type of constant expression.`);
}

View file

@ -123,23 +123,27 @@ class DeepMap {
}
export function memoize(target: any, key: PropertyKey) {
export function memoize(hasher: (...args: any[]) => string) {
return function (target: any, key: PropertyKey) {
const origMethod = target[key];
target[key] = function wrapper(...args: any[]) {
if (this.__MEMOIZE_CACHE === undefined) {
this.__MEMOIZE_CACHE = Object.create(null);
}
if (this.__MEMOIZE_CACHE[key] === undefined) {
this.__MEMOIZE_CACHE[key] = new DeepMap();
this.__MEMOIZE_CACHE[key] = Object.create(null);
}
const hashed = hasher(...args);
const cache = this.__MEMOIZE_CACHE[key];
if (cache.has(args)) {
return cache.get(args);
if (hashed in cache) {
return cache[hashed];
}
const result = origMethod.apply(this, args);
cache.set(args, result);
cache[hashed] = result;
return result;
}
return target;
}
}
const supportedLanguages = ['Bolt', 'JS'];