Created
July 27, 2020 04:13
-
-
Save poberwong/cf86bf7d3cc7896cfba8e60d812f4497 to your computer and use it in GitHub Desktop.
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
/** | |
* if immediate is true, the value will be returned synchronously or else will return a Promise | |
* @returns {Function} | |
*/ | |
export const debounce = (params: Object = {}) => (target: any, name: any, descriptor: any) => { | |
let timer = null | |
const { delay = 300, immediate = false } = params | |
// high order function | |
if (!descriptor || (arguments.length === 1 && typeof target === 'function')) { | |
return createDebounce(target) | |
} | |
function createDebounce (fn): any { | |
return function debounce () { | |
if (immediate && !timer) { | |
return fn.apply(this, arguments) | |
} | |
if (timer) { | |
clearTimeout(timer) | |
} | |
let argumentsCopy = arguments | |
let that = this | |
return (new Promise((resolve) => { | |
timer = setTimeout(function () { | |
if (!immediate) { | |
resolve(fn.apply(that, argumentsCopy)) | |
} | |
timer = null | |
}, delay) | |
})) | |
} | |
} | |
if (descriptor.value) { | |
return { | |
enumerable: false, | |
configurable: true, | |
writable: true, | |
value: createDebounce(descriptor.value) | |
} | |
} | |
if (descriptor.initializer) { | |
return { | |
enumerable: false, | |
configurable: true, | |
writable: true, | |
initializer () { | |
return createDebounce(descriptor.initializer.call(this)) | |
} | |
} | |
} | |
return descriptor | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment