1
0
mirror of https://github.com/flarum/core.git synced 2025-07-10 11:26:24 +02:00
Files
php-flarum/js/src/common/utils/computed.ts
David Wheatley d268894e61 chore: 1.2 JS clean-up (#3214)
* fix: `extend.ts` TS error

* docs: fix incorrect JS docblocks

* chore: simplify some code

* chore: remove usages of prefixed JS function

* chore: consistent empty return types

* chore: format

* fix: typing errors

* chore: remove unneeded `@public` docblock modifiers

* Apply suggestions from code review

* Update js/src/forum/utils/slidable.js

Co-authored-by: Alexander Skvortsov <38059171+askvortsov1@users.noreply.github.com>

* Apply suggestions from code review

Co-authored-by: Alexander Skvortsov <38059171+askvortsov1@users.noreply.github.com>
2021-12-27 18:58:18 +00:00

43 lines
1.3 KiB
TypeScript

import Model from '../Model';
/**
* The `computed` utility creates a function that will cache its output until
* any of the dependent values are dirty.
*
* @param dependentKeys The keys of the dependent values.
* @param compute The function which computes the value using the
* dependent values.
*/
export default function computed<T, M = Model>(...args: [...string[], (this: M, ...args: unknown[]) => T]): () => T {
const keys = args.slice(0, -1) as string[];
const compute = args.slice(-1)[0] as (this: M, ...args: unknown[]) => T;
const dependentValues: Record<string, unknown> = {};
let computedValue: T;
return function (this: M) {
let recompute = false;
// Read all of the dependent values. If any of them have changed since last
// time, then we'll want to recompute our output.
keys.forEach((key) => {
const attr = (this as Record<string, unknown | (() => unknown)>)[key];
const value = typeof attr === 'function' ? attr.call(this) : attr;
if (dependentValues[key] !== value) {
recompute = true;
dependentValues[key] = value;
}
});
if (recompute) {
computedValue = compute.apply(
this,
keys.map((key) => dependentValues[key])
);
}
return computedValue;
};
}