Skip to content

Instantly share code, notes, and snippets.

@Niryo

Niryo/effect.ts Secret

Created Sep 5, 2020
Embed
What would you like to do?
naive effect implementation
type ClearEffectFN = (() => void) | undefined;
type EffectFN = (...args: any[]) => ClearEffectFN;
function effect(fn: EffectFN) {
let prevParams: any[] | undefined = undefined;
let clearFN: ClearEffectFN = undefined;
return (...params: any[]) => {
if (prevParams === undefined || isChanged(prevParams, params)) {
if (typeof clearFN === 'function') {
clearFN();
}
clearFN = fn(...params);
}
prevParams = params;
}
}
function isChanged(prevParams: any[], currentParams: any[]) {
let isChanged = false;
prevParams.forEach((param, index) => {
if (param !== currentParams[index]) {
isChanged = true;
}
});
return isChanged;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment