Last active
March 5, 2025 14:13
-
-
Save colelawrence/bfc11379c95238f7389b719b15099f23 to your computer and use it in GitHub Desktop.
Loop protection counter in TypeScript
This file contains hidden or 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
import { DevError, debounce } from "@project/prelude"; | |
export class LoopError extends DevError { | |
constructor( | |
message: string, | |
public readonly debounceMs: number, | |
public readonly maxCount: number, | |
) { | |
super(`${message} (exceeded ${maxCount} calls in ${(debounceMs * 0.001).toFixed(1)}s)`); | |
} | |
} | |
export function createCounterWithLoopProtection({ debounceMs = 1000, maxCount = 20, message = "loop detected" } = {}) { | |
let count = 0; | |
let max = maxCount; | |
const scheduleClearLoopDetection = debounce(debounceMs, () => { | |
max = count + maxCount; | |
}); | |
return () => { | |
count++; | |
scheduleClearLoopDetection(); | |
if (count > max) { | |
throw new LoopError(message, debounceMs, maxCount); | |
} | |
return count; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment