Last active
September 26, 2023 14:15
-
-
Save LeonardoZivieri/2a9b19a3c521bfd18b452c550ba61f0f to your computer and use it in GitHub Desktop.
Angular GetterMemo, to prevent recalculations based on a list of values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default class GetterMemo<V, C extends any[] = any[]> { | |
constructor( | |
private _calculator: () => V, | |
private _valueSeparators: () => C | |
) {} | |
private _lastValue?: V; | |
private _lastUpdate?: C; | |
clear() { | |
this._lastValue = undefined; | |
this._lastUpdate = undefined; | |
} | |
reload() { | |
this.clear(); | |
return this.getValue(); | |
} | |
check(current = this._valueSeparators()) { | |
const lastUpdate = this._lastUpdate; | |
if (lastUpdate) { | |
if (current.every((_, i) => current[i] === lastUpdate[i])) { | |
return false; | |
} | |
} | |
return true; | |
} | |
getValue() { | |
const current = this._valueSeparators(); | |
if (this.check(current)) { | |
this._lastValue = this._calculator(); | |
this._lastUpdate = current; | |
} | |
return this._lastValue as V; | |
} | |
} | |
/** | |
How to use | |
public input = "1,2,3,4,5,6,7,8,9" | |
private _oddNumbers = new GetterCache( | |
// First Parameter: the calculation function, will be disponible in GetterCache.getValue | |
() => input.split(",").map(n => parseInt(n, 10)).filter(n => !isNaN(n) && n % 2 == 1), | |
// Second Parameter: A list of values to === compare with the last list | |
() => [this.input] | |
); | |
get odd() { | |
return this._oddNumbers.getValue(); | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment