Implement custom throttle function for performance

This commit is contained in:
Jon Staab
2024-12-11 16:41:31 -08:00
parent ab0517e804
commit 0fcb2482d8
12 changed files with 68 additions and 34 deletions
+1 -3
View File
@@ -32,9 +32,7 @@
},
"dependencies": {
"@types/events": "^3.0.3",
"@types/throttle-debounce": "^5.0.2",
"@scure/base": "^1.1.6",
"events": "^3.3.0",
"throttle-debounce": "^5.0.0"
"events": "^3.3.0"
}
}
+31 -2
View File
@@ -1,4 +1,3 @@
import {throttle} from 'throttle-debounce'
import {bech32, utf8} from "@scure/base"
// Dealing with nil
@@ -298,7 +297,7 @@ export const choice = <T>(xs: T[]): T => xs[Math.floor(xs.length * Math.random()
export const shuffle = <T>(xs: Iterable<T>): T[] => Array.from(xs).sort(() => Math.random() > 0.5 ? 1 : -1)
export const sample = <T>(n: number, xs: T[]) => shuffle(xs).slice(0, n)
export const samplo = <T>(n: number, xs: T[]) => shuffle(xs).slice(0, n)
export const isIterable = (x: any) => Symbol.iterator in Object(x)
@@ -459,6 +458,36 @@ export const memoize = <T>(f: (...args: any[]) => T) => {
}
}
export const throttle = <F extends (...args: any[]) => any>(ms: number, f: F) => {
if (ms === 0) {
return f
}
let args: Parameters<F>
let paused = false
let trailing = false
const unpause = () => {
if (trailing) {
f(...args)
trailing = false
}
paused = false
}
return (...thisArgs: Parameters<F>) => {
if (!paused) {
f(...thisArgs)
paused = true
args = thisArgs
setTimeout(unpause, ms)
} else {
trailing = true
}
}
}
export const throttleWithValue = <T>(ms: number, f: () => T) => {
let value: T