Cache some volatile conversation properties
This commit is contained in:
parent
ba79595563
commit
f92f81dfd6
6 changed files with 157 additions and 92 deletions
20
ts/util/memoizeByThis.ts
Normal file
20
ts/util/memoizeByThis.ts
Normal file
|
@ -0,0 +1,20 @@
|
|||
// Copyright 2022 Signal Messenger, LLC
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
import { isEqual } from 'lodash';
|
||||
|
||||
export function memoizeByThis<Owner extends Record<string, unknown>, Result>(
|
||||
fn: () => Result
|
||||
): () => Result {
|
||||
const lastValueMap = new WeakMap<Owner, Result>();
|
||||
return function memoizedFn(this: Owner): Result {
|
||||
const lastValue = lastValueMap.get(this);
|
||||
const newValue = fn();
|
||||
if (lastValue !== undefined && isEqual(lastValue, newValue)) {
|
||||
return lastValue;
|
||||
}
|
||||
|
||||
lastValueMap.set(this, newValue);
|
||||
return newValue;
|
||||
};
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue