Skip to content

Instantly share code, notes, and snippets.

@bramblex
Last active October 30, 2018 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bramblex/87a36b16f587052db209529bf1dd553a to your computer and use it in GitHub Desktop.
Save bramblex/87a36b16f587052db209529bf1dd553a to your computer and use it in GitHub Desktop.
用于限流
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
}
}
}
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