Skip to content

Instantly share code, notes, and snippets.

@jlozovei
Created February 14, 2023 16:21
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 jlozovei/5fa672b3983b76a8b32f6c956658cd87 to your computer and use it in GitHub Desktop.
Save jlozovei/5fa672b3983b76a8b32f6c956658cd87 to your computer and use it in GitHub Desktop.
Useful JS scripts and snippets
const debounce = (func, delay) => {
let inDebounce;
return function() {
const context = this;
const args = arguments;
clearTimeout(inDebounce);
inDebounce = setTimeout(() => func.apply(context, args), delay);
}
}
// usage: debounce(() => { console.log('debounced'); }, 1000);
// inspired by https://davidwalsh.name/query-string-javascript
function getURLParam(param) {
return (
decodeURIComponent(
(new RegExp(
'[?|&]' + param + '=' + '([^&;]+?)(&|#|;|$)'
).exec(location.search) || [, ''])[1].replace(/\+/g, '%20')
) || null
);
}
// Usage: getURLParam('q')
/*
* Updated using URLSearchParam
*/
const searchParam = new URLSearchParams(location.search);
searchParam.get('q');
const throttle = (func, limit) => {
let inThrottle;
return function() {
const args = arguments;
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
}
}
// usage: throttle(() => { console.log('throttled') }, 200);
// recursive path walker
function walk(dir, extension, done) {
let results = [];
fs.readdir(dir, (err, list) => {
if (err) return done(err);
let pending = list.length;
if (!pending) return done(null, results);
list.forEach(file => {
file = path.resolve(dir, file);
fs.stat(file, (err, stat) => {
if (stat && stat.isDirectory()) {
walk(file, extension, (err, res) => {
results = results.concat(res);
if (!--pending) done(null, results);
});
} else {
if (file.substr(file.lastIndexOf('.') + 1, file.length).toLowerCase() === extension) results.push(file);
if (!--pending) done(null, results);
}
});
});
});
}
// usage
walk(
path.resolve('./dev/'),
'js',
(err, results) => {
// results is the array of files
console.log(results);
if (err) console.error(err);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment