naive effect implementation
This file contains 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
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