|
911 | 911 | "author": "axorax"
|
912 | 912 | },
|
913 | 913 | {
|
914 |
| - "title": "Random string", |
915 |
| - "description": "Generates a random string of characters of a certain length", |
916 |
| - "code": [ |
917 |
| - "function makeid(length, characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {", |
918 |
| - " return Array.from({ length }, () => characters.charAt(Math.floor(Math.random() * characters.length))).join('');", |
919 |
| - "}", |
| 914 | + "title": "Rate Limit Function", |
| 915 | + "description": "Limits how often a function can be executed within a given time window.", |
| 916 | + "code": [ |
| 917 | + "const rateLimit = (func, limit, timeWindow) => {", |
| 918 | + " let queue = [];", |
| 919 | + " setInterval(() => {", |
| 920 | + " if (queue.length) {", |
| 921 | + " const next = queue.shift();", |
| 922 | + " func(...next.args);", |
| 923 | + " }", |
| 924 | + " }, timeWindow);", |
| 925 | + " return (...args) => {", |
| 926 | + " if (queue.length < limit) {", |
| 927 | + " queue.push({ args });", |
| 928 | + " }", |
| 929 | + " };", |
| 930 | + "};", |
920 | 931 | "",
|
921 |
| - "console.log(makeid(5), \"1234\" /* (optional) */);" |
| 932 | + "// Usage:", |
| 933 | + "const fetchData = () => console.log('Fetching data...');", |
| 934 | + "const rateLimitedFetch = rateLimit(fetchData, 2, 1000);", |
| 935 | + "setInterval(() => rateLimitedFetch(), 200); // Only calls fetchData twice every second" |
922 | 936 | ],
|
923 |
| - "tags": ["javascript", "function", "random"], |
924 |
| - "author": "kruimol" |
| 937 | + "tags": ["javascript", "function", "rate-limiting", "utility"], |
| 938 | + "author": "axorax" |
925 | 939 | }
|
926 | 940 | ]
|
927 | 941 | },
|
|
0 commit comments