Last active
October 30, 2018 09:22
-
-
Save bramblex/87a36b16f587052db209529bf1dd553a 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
export function throttle<R>(func: () => Promise<R>): () => Promise<R> { | |
let promise: Promise<R> | null = null | |
return () => { | |
if (promise) { | |
return promise | |
} else { | |
promise = func() | |
promise.finally(() => promise = null) | |
return promise | |
} | |
} | |
} |
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
export function throttle<Args extends any[], R>(func: (...args: Args) => Promise<R>): (...args: Args) => Promise<R> { | |
function hash(str: string): number { | |
let nr = 1 | |
let nr2 = 4 | |
for (let i = 0; i < str.length; i++) { | |
nr ^= (((nr & 63) + nr2) * (str.charCodeAt(i))) + (nr << 8) | |
nr2 += 3 | |
} | |
return nr | |
} | |
function hashArgs(args: Args): number { | |
return hash(JSON.stringify(args)) | |
} | |
const promises: { [key: number]: Promise<R> } = {} | |
return (...args: Args) => { | |
const key = hashArgs(args) | |
if (promises[key]) { | |
return promises[key] | |
} else { | |
const promise = func(...args) | |
promises[key] = promise | |
promise.finally(() => delete promises[key]) | |
return promise | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment