summaryrefslogtreecommitdiff
path: root/src/misc/utils.ts
blob: 7c2a577b4fee35281367212e2d545157227865df (plain)
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
export function throttle<T extends any[]>(
  fn: (...args: T) => unknown,
  timeout: number
) {
  let pending = false;

  return (...args: T) => {
    if (!pending) {
      pending = true;
      fn(...args);
      setTimeout(() => {
        pending = false;
      }, timeout);
    }
  };
}

export function debounce<T extends any[]>(
  fn: (...args: T) => unknown,
  timeout: number
) {
  let timeoutId: ReturnType<typeof setTimeout>;
  return (...args: T) => {
    if (timeoutId) clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      fn(...args);
    }, timeout);
  };
}

export function trimTrailingSlash(s: string) {
  return s.replace(/\/$/, '');
}