add memoize function and use it for makeEnvironment

This commit is contained in:
Géry Debongnie
2019-01-27 09:23:48 +01:00
parent d68198ad34
commit 0dfa47e405
4 changed files with 60 additions and 5 deletions
+1 -1
View File
@@ -15,7 +15,7 @@ let wl: any[] = [];
(<any>window).wl = wl;
interface Meta<T extends WEnv> {
id: number;
readonly id: number;
// name: string;
// template: string;
vnode: VNode | null;
+20
View File
@@ -31,3 +31,23 @@ export function idGenerator(): (() => number) {
let nextID = 1;
return () => nextID++;
}
export type HashFn = (args: any[]) => string;
export function memoize<R, T extends (...args: any[]) => R>(
f: T,
hash?: HashFn
): T {
if (!hash) {
hash = args => args.map(a => String(a)).join(",");
}
let cache: { [key: string]: R } = {};
function memoizedFunction(...args: any[]) {
let hashValue = hash!(args);
if (!(hashValue in cache)) {
cache[hashValue] = f(...args);
}
return cache[hashValue];
}
return memoizedFunction as T;
}
+13 -3
View File
@@ -1,5 +1,5 @@
import { QWeb } from "./core/qweb_vdom";
import { idGenerator } from "./core/utils";
import { idGenerator, memoize } from "./core/utils";
import { WEnv } from "./core/widget";
import { ActionManager, IActionManager } from "./services/action_manager";
import { Ajax, IAjax } from "./services/ajax";
@@ -32,7 +32,17 @@ export interface Env extends WEnv {
// Code
//------------------------------------------------------------------------------
export function makeEnvironment(): Env {
/**
* makeEnvironment returns the main environment for the application.
*
* Note that it does not make much sense (except for tests) to have more than
* one environment. For example, with two environment, the router code in one
* environment will probably interfere with the code from the other environment.
*
* For this reason, the result of makeEnvironment is memoized: every call to
* this function will actually return the same environment.
*/
export const makeEnvironment = memoize(function(): Env {
const qweb = new QWeb();
const router = new Router();
const ajax = new Ajax();
@@ -55,4 +65,4 @@ export function makeEnvironment(): Env {
rpc: ajax.rpc,
debug: false
};
}
});