UNPKG

@j03fr0st/pubg-ts

Version:

A comprehensive TypeScript wrapper for the PUBG API

43 lines (33 loc) 1.22 kB
export class RateLimiter { private requests: number[] = []; private maxRequests: number; private windowMs: number; constructor(maxRequests: number = 10, windowMs: number = 60000) { this.maxRequests = maxRequests; this.windowMs = windowMs; } async waitForSlot(): Promise<void> { const now = Date.now(); this.requests = this.requests.filter((time) => now - time < this.windowMs); if (this.requests.length >= this.maxRequests) { const oldestRequest = Math.min(...this.requests); const waitTime = this.windowMs - (now - oldestRequest); if (waitTime > 0) { await new Promise((resolve) => setTimeout(resolve, waitTime)); return this.waitForSlot(); } } this.requests.push(now); } getRemainingRequests(): number { const now = Date.now(); this.requests = this.requests.filter((time) => now - time < this.windowMs); return Math.max(0, this.maxRequests - this.requests.length); } getResetTime(): number { if (this.requests.length === 0) return 0; const _now = Date.now(); const oldestRequest = Math.min(...this.requests); return oldestRequest + this.windowMs; } }