diff options
author | Vendicated <vendicated@riseup.net> | 2022-11-25 18:07:29 +0100 |
---|---|---|
committer | Vendicated <vendicated@riseup.net> | 2022-11-25 18:07:29 +0100 |
commit | b60f6cb18d1d55d367ae2f3c322d76b709eacdfe (patch) | |
tree | c2d06ff7643da8244c157c03e877b273b5b61a39 /src/utils | |
parent | bb398970ef7d60c68191f5e6e153bdba24e07207 (diff) | |
download | Vencord-b60f6cb18d1d55d367ae2f3c322d76b709eacdfe.tar.gz Vencord-b60f6cb18d1d55d367ae2f3c322d76b709eacdfe.tar.bz2 Vencord-b60f6cb18d1d55d367ae2f3c322d76b709eacdfe.zip |
WhoReacted: Make more reliable & don't spam api
Diffstat (limited to 'src/utils')
-rw-r--r-- | src/utils/Queue.ts | 45 | ||||
-rw-r--r-- | src/utils/misc.tsx | 5 |
2 files changed, 47 insertions, 3 deletions
diff --git a/src/utils/Queue.ts b/src/utils/Queue.ts index 46959a0..6153d40 100644 --- a/src/utils/Queue.ts +++ b/src/utils/Queue.ts @@ -19,9 +19,48 @@ import { Promisable } from "type-fest"; export class Queue { - private promise: Promise<any> = Promise.resolve(); + /** + * @param maxSize The maximum amount of functions that can be queued at once. + * If the queue is full, the oldest function will be removed. + */ + constructor(public maxSize = Infinity) { } - add<T>(func: (lastValue: unknown) => Promisable<T>): Promise<T> { - return (this.promise = this.promise.then(func)); + queue = [] as Array<() => Promisable<unknown>>; + + private promise?: Promise<any>; + + private next() { + const func = this.queue.shift(); + if (func) + this.promise = Promise.resolve() + .then(func) + .then(() => this.next()); + else + this.promise = undefined; + } + + private run() { + if (!this.promise) + this.next(); + } + + push<T>(func: () => Promisable<T>) { + if (this.size >= this.maxSize) + this.queue.shift(); + + this.queue.push(func); + this.run(); + } + + unshift<T>(func: () => Promisable<T>) { + if (this.size >= this.maxSize) + this.queue.pop(); + + this.queue.unshift(func); + this.run(); + } + + get size() { + return this.queue.length; } } diff --git a/src/utils/misc.tsx b/src/utils/misc.tsx index 005bcc0..44fc819 100644 --- a/src/utils/misc.tsx +++ b/src/utils/misc.tsx @@ -70,6 +70,11 @@ export function useAwaiter<T>(factory: () => Promise<T>, fallbackValue: T | null return [state.value, state.error, state.pending, () => setSignal(signal + 1)]; } +export function useForceUpdater() { + const [, set] = React.useState(0); + return () => set(s => s + 1); +} + /** * A lazy component. The factory method is called on first render. For example useful * for const Component = LazyComponent(() => findByDisplayName("...").default) |