6. Throttle Function (Control Function Call Rate)
function throttle(fn, wait) {
let lastTime = 0;
return function (...args) {
const now = Date.now();
if (now - lastTime >= wait) {
lastTime = now;
fn.apply(this, args);
}
};
}
// Usage
const throttledLog = throttle(console.log, 2000);
throttledLog('This will log immediately');
throttledLog('This will be ignored if called within 2 seconds');
7. Recursive Directory Traversal (Async, Promises)
const fs = require('fs').promises;
const path = require('path');
async function walkDir(dir, fileList = []) {
const files = await fs.readdir(dir);
for (const file of files) {
const filePath = path.join(dir, file);
const stat = await fs.stat(filePath);
if (stat.isDirectory()) {
await walkDir(filePath, fileList);
} else {
fileList.push(filePath);
}
}
return fileList;
}
// Usage
// walkDir('./some-directory').then(console.log);
8. Simple Event Emitter Implementation
class SimpleEventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
(this.events[event] = this.events[event] || []).push(listener);
}
emit(event, ...args) {
(this.events[event] || []).forEach((listener) => listener(...args));
}
off(event, listener) {
if (!this.events[event]) return;
this.events[event] = this.events[event].filter((l) => l !== listener);
}
}
// Usage
// const emitter = new SimpleEventEmitter();
// emitter.on('data', (msg) => console.log(msg));
// emitter.emit('data', 'Hello!');
9. Timeout a Promise
function promiseTimeout(promise, ms) {
let timeout = new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), ms));
return Promise.race([promise, timeout]);
}
// Usage
// promiseTimeout(fetch('https://example.com'), 1000).catch(console.error);
10. Stream File Line by Line (No External Libraries)
const fs = require('fs');
const readline = require('readline');
function readLines(filePath, onLine) {
const rl = readline.createInterface({
input: fs.createReadStream(filePath),
crlfDelay: Infinity,
});
rl.on('line', onLine);
rl.on('close', () => console.log('Done reading file.'));
}
// Usage
// readLines('./file.txt', line => console.log('Line:', line));