File tree Expand file tree Collapse file tree 2 files changed +27
-2
lines changed
javascript-utilities/throttle Expand file tree Collapse file tree 2 files changed +27
-2
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ The GFE 75 is GreatFrontEnd's curated collection of 75 essential frontend coding
1010
1111| Category | Completed | Total | Percentage |
1212| -------------------- | --------- | ----- | ---------- |
13- | JavaScript Utilities | 3 | 30 | 10% |
13+ | JavaScript Utilities | 3 | 20 | 10% |
1414| DOM Manipulation | 0 | 15 | 0% |
1515| Async Programming | 0 | 12 | 0% |
1616| Components | 0 | 10 | 0% |
@@ -23,6 +23,7 @@ The GFE 75 is GreatFrontEnd's curated collection of 75 essential frontend coding
2323
2424- [ Debounce] ( ./javascript-utilities/debounce/ ) - Medium
2525- [ Flatten] ( ./javascript-utilities/flatten/ ) - Medium
26+ - [ Throttle] ( ./javascript-utilities/throttle/ ) - Medium
2627
2728### DOM Manipulation (0/15)
2829
Original file line number Diff line number Diff line change 1+ /**
2+ * Throttle a function so that it can only be called once per wait period.
3+ * @time O(1) for each call
4+ * @space O(1) for the closure variables
5+ */
6+
17/* eslint-disable @typescript-eslint/no-explicit-any */
28type ThrottleFn < T extends any [ ] > = ( ...args : T ) => any ;
39
10+ function validateFunc < T extends any [ ] > ( fn : ThrottleFn < T > ) : void {
11+ if ( typeof fn !== 'function' ) {
12+ throw new TypeError ( 'First argument must be a function' ) ;
13+ }
14+ }
15+
16+ function validateWait ( wait : number ) : void {
17+ if ( typeof wait !== 'number' || wait < 0 || ! Number . isFinite ( wait ) ) {
18+ throw new TypeError ( 'Wait must be a non-negative finite number' ) ;
19+ }
20+ }
21+
422// Leading edge with timestamp
5- export default function throttle < T extends any [ ] > (
23+ export function throttle < T extends any [ ] > (
624 func : ThrottleFn < T > ,
725 wait : number
826) : ThrottleFn < T > {
27+ validateFunc ( func ) ;
28+ validateWait ( wait ) ;
29+
930 let lastCallTime = 0 ;
1031
1132 return function ( this : any , ...args : T ) {
@@ -22,6 +43,9 @@ export function throttleTrailingEdge<T extends any[]>(
2243 func : ThrottleFn < T > ,
2344 wait : number
2445) : ThrottleFn < T > {
46+ validateFunc ( func ) ;
47+ validateWait ( wait ) ;
48+
2549 let timeoutId : ReturnType < typeof setTimeout > | null = null ;
2650 let lastArgs : T | undefined ;
2751
You can’t perform that action at this time.
0 commit comments