Last active
August 4, 2022 14:57
-
-
Save gera2ld/e13b0b564b38addfebe46dc329317064 to your computer and use it in GitHub Desktop.
JavaScript utilities
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Readable } from 'stream'; | |
export function string2stream(stringOrBuffer) { | |
const reader = new Readable(); | |
reader.push(stringOrBuffer); | |
reader.push(null); | |
return reader; | |
} | |
export function stream2buffer(stream) { | |
return new Promise((resolve, reject) => { | |
const chunks = []; | |
stream.on('data', chunk => { | |
chunks.push(chunk); | |
}); | |
stream.on('end', () => { | |
const buffer = Buffer.concat(chunks); | |
resolve(buffer); | |
}); | |
stream.on('error', e => { | |
reject(e); | |
}); | |
}); | |
} | |
export function escapeRegExp(string) { | |
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); | |
} | |
export function escapeHtml(string) { | |
return string.replace(/[&<]/g, m => ({ | |
'&': '&', | |
'<': '<', | |
}[m])); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function debounce(func, wait, options) { | |
const { maxWait } = { | |
...options, | |
}; | |
let startTime; | |
let lastTime = 0; | |
let timer; | |
let callback; | |
let result; | |
wait = Math.max(0, +wait || 0); | |
function checkTime() { | |
timer = null; | |
const now = performance.now(); | |
if (now >= startTime) { | |
lastTime = now; | |
callback(); | |
} else { | |
checkTimer(); | |
} | |
} | |
function checkTimer() { | |
if (!timer) { | |
const delta = startTime - performance.now(); | |
timer = setTimeout(checkTime, delta); | |
} | |
} | |
function debouncedFunction(...args) { | |
const now = performance.now(); | |
startTime = maxWait && now < lastTime + maxWait ? lastTime + maxWait : now + wait; | |
callback = () => { | |
callback = null; | |
lastTime = performance.now(); | |
result = func.apply(this, args); | |
}; | |
checkTimer(); | |
return result; | |
} | |
return debouncedFunction; | |
} | |
export function throttle(func, wait) { | |
let lastTime = 0; | |
let result; | |
wait = Math.max(0, +wait || 0); | |
function throttledFunction(...args) { | |
const now = performance.now(); | |
if (lastTime + wait < now) { | |
lastTime = now; | |
result = func.apply(this, args); | |
} | |
return result; | |
} | |
return throttledFunction; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment