Skip to content

Instantly share code, notes, and snippets.

@Niryo

Niryo/effect.ts Secret

Created September 5, 2020 10:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Niryo/82127a23af88b45f7668146f5a866aa2 to your computer and use it in GitHub Desktop.
Save Niryo/82127a23af88b45f7668146f5a866aa2 to your computer and use it in GitHub Desktop.
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