Skip to content

Instantly share code, notes, and snippets.

@gera2ld
Last active August 4, 2022 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gera2ld/e13b0b564b38addfebe46dc329317064 to your computer and use it in GitHub Desktop.
Save gera2ld/e13b0b564b38addfebe46dc329317064 to your computer and use it in GitHub Desktop.
JavaScript utilities
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 => ({
'&': '&amp;',
'<': '&lt;',
}[m]));
}
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