/
index.ts
47 lines (44 loc) · 1.05 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { Subject } from 'rxjs'
import { debounceTime, throttleTime } from 'rxjs/operators'
/**
* Generate a debounced Function base on the actual function
* Debounced execute after time
* @param fn
* @param time
* @category Tools
* @example
* ```ts
* const debouncePatch = debounce( async (body) => {
* await client.id('12345').patch(body);
* },200)
*
* ...
* debouncePatch(body)
*
* ```
*/
const debounce = <T extends Function>(fn: T, time: number): Function => {
const observable = new Subject<any[]>()
observable.pipe(debounceTime(time)).subscribe((args: any[]) => {
return fn(...args)
})
return (...args: any[]) => {
observable.next(args)
}
}
/**
* Throttle execution within time
* @param fn
* @param time
* @category Tools
*/
const throttle = <T extends Function>(fn: T, time: number): Function => {
const observable = new Subject<any[]>()
observable.pipe(throttleTime(time)).subscribe((args: any[]) => {
return fn(...args)
})
return (...args: any[]) => {
observable.next(args)
}
}
export { debounce, throttle }