Node.js Interview Coding Problems & Solutions
Master backend Node.js coding rounds with 200 practical coding problems, event emitters, streams, cluster modules, and expert solutions.
Q1. Implement a custom EventEmiiter class from scratch
class EventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
if (!this.events[event]) this.events[event] = [];
this.events[event].push(listener);
}
emit(event, ...args) {
if (this.events[event]) {
this.events[event].forEach(listener => listener(...args));
}
}
off(event, listenerToRemove) {
if (!this.events[event]) return;
this.events[event] = this.events[event].filter(listener => listener !== listenerToRemove);
}
}
// Usage:
const emitter = new EventEmitter();
emitter.on('greet', name => console.log('Hello ' + name));
emitter.emit('greet', 'Node.js');Builds a publish-subscribe event emitter mechanism managing listener callback arrays.
Q2. Read a large file line by line using ReadStreams and ReadLine
const fs = require('fs');
const readline = require('readline');
async function processLineByLine(filePath) {
const fileStream = fs.createReadStream(filePath);
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
for await (const line of rl) {
console.log('Line from file:', line);
}
}
processLineByLine('./large-log.txt');Streams massive log files line by line asynchronously without overflowing V8 heap memory.
Q3. Implement a custom Promise.all implementation
function promiseAll(promises) {
return new Promise((resolve, reject) => {
if (!Array.isArray(promises)) return reject(new TypeError('Arguments must be an array'));
const results = [];
let completed = 0;
if (promises.length === 0) return resolve(results);
promises.forEach((promise, index) => {
Promise.resolve(promise)
.then(value => {
results[index] = value;
completed++;
if (completed === promises.length) resolve(results);
})
.catch(reject);
});
});
}Resolves when all input promises fulfill, or rejects immediately if any promise rejects.
Q4. Implement rate limiter middleware in Express.js
const rateLimit = require('express-rate-limit');
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
message: 'Too many requests from this IP, please try again later',
standardHeaders: true,
legacyHeaders: false,
});
// Usage in Express app:
// app.use('/api/', apiLimiter);Protects backend API endpoints against abuse by throttling client request frequencies.
Q5. Implement Cluster module load balancer setup
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isPrimary) {
console.log('Primary process ' + process.pid + ' is running');
for (let i = 0; i < numCPUs; i++) cluster.fork();
cluster.on('exit', (worker) => {
console.log('Worker ' + worker.process.pid + ' died. Forking new one...');
cluster.fork();
});
} else {
http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello from worker ' + process.pid);
}).listen(8000);
}Spawns child worker processes sharing port bindings to utilize multi-core CPU architectures.
Q6. Implement JWT Authentication Middleware
const jwt = require('jsonwebtoken');
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) return res.sendStatus(401);
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}Verifies bearer tokens in request headers to protect private API routes.
Q7. Build a simple caching middleware using Map
const cache = new Map();
function cacheMiddleware(duration) {
return (req, res, next) => {
const key = req.originalUrl || req.url;
const cachedResponse = cache.get(key);
if (cachedResponse) {
return res.send(cachedResponse);
}
res.sendResponse = res.send;
res.send = (body) => {
cache.set(key, body);
setTimeout(() => cache.delete(key), duration * 1000);
res.sendResponse(body);
};
next();
};
}Caches HTTP responses in memory for high-speed retrieval.
Q8. Implement graceful shutdown handling
const express = require('express');
const app = express();
const server = app.listen(3000);
process.on('SIGTERM', () => {
console.log('SIGTERM signal received: closing HTTP server');
server.close(() => {
console.log('HTTP server closed');
// Close database connections here
process.exit(0);
});
});Ensures ongoing active requests complete successfully before shutting down server processes.
Q9. Implement a debounce helper function in Node
function debounce(fn, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
// Usage: const debouncedLog = debounce(() => console.log('called'), 300);Delays function executions until specified idle time intervals elapse.
Q10. Hash passwords securely using bcrypt
const bcrypt = require('bcrypt');
async function hashPassword(plainPassword) {
const saltRounds = 10;
const hash = await bcrypt.hash(plainPassword, saltRounds);
return hash;
}
async function verifyPassword(plainPassword, hash) {
return await bcrypt.compare(plainPassword, hash);
}Salts and hashes passwords securely prior to database persistence.
Q11. Implement a custom Promise.race implementation
function promiseRace(promises) {
return new Promise((resolve, reject) => {
for (let p of promises) {
Promise.resolve(p).then(resolve, reject);
}
});
}Returns a promise that fulfills or rejects as soon as one of the input promises settles.
Q12. Implement deep clone function for JavaScript objects
function deepClone(obj, hash = new WeakMap()) {
if (Object(obj) !== obj) return obj;
if (hash.has(obj)) return hash.get(obj);
let result = obj instanceof Date ? new Date(obj)
: obj instanceof RegExp ? new RegExp(obj.source, obj.flags)
: obj.constructor ? new obj.constructor() : Object.create(null);
hash.set(obj, result);
return Object.assign(result, ...Object.keys(obj).map(key => ({ [key]: deepClone(obj[key], hash) })));
}Recursively clones complex nested objects handling circular references.
Q13. Implement basic connection pooling simulation
class ConnectionPool {
constructor(maxSize) {
this.maxSize = maxSize;
this.pool = [];
this.active = 0;
}
acquire() {
if (this.pool.length > 0) return this.pool.pop();
if (this.active < this.maxSize) {
this.active++;
return { id: Math.random() };
}
return null;
}
release(conn) {
this.pool.push(conn);
}
}Manages finite database connection resource pools efficiently.
Q14. Implement custom Error handling middleware in Express
function errorHandler(err, req, res, next) {
const statusCode = err.statusCode || 500;
res.status(statusCode).json({
success: false,
error: {
message: err.message,
status: statusCode,
}
});
}Captures unhandled errors across Express routes and formats standard JSON error responses.
Q15. Implement a file logger utility class
const fs = require('fs');
const path = require('path');
class Logger {
constructor(filename) {
this.filepath = path.join(__dirname, filename);
}
log(message) {
const entry = `[${new Date().toISOString()}] ${message}\n`;
fs.appendFile(this.filepath, entry, (err) => {
if (err) console.error('Logging failed:', err);
});
}
}Appends timestamped log records into physical files asynchronously.
Q16. Create a simple TCP Echo Server using net module
const net = require('net');
const server = net.createServer((socket) => {
console.log('Client connected');
socket.on('data', (data) => {
socket.write('Echo: ' + data);
});
socket.on('end', () => console.log('Client disconnected'));
});
server.listen(8080, () => console.log('TCP server listening on port 8080'));Listens for raw TCP socket data streams and echoes back data.
Q17. Build a simple UDP Server using dgram module
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.on('message', (msg, rinfo) => {
console.log(`Server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
server.bind(41234);Handles connectionless UDP datagram message packets.
Q18. Implement request body parser middleware from scratch
function bodyParser(req, res, next) {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
req.body = JSON.parse(body);
} catch (e) {
req.body = {};
}
next();
});
}Collects incoming HTTP request chunk buffers and parses JSON payloads.
Q19. Implement a worker thread CPU-bound task runner
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
if (isMainThread) {
module.exports = function runWorker(data) {
return new Promise((resolve, reject) => {
const worker = new Worker(__filename, { workerData: data });
worker.on('message', resolve);
worker.on('error', reject);
});
};
} else {
const result = workerData * 1000;
parentPort.postMessage(result);
}Offloads heavy calculations to parallel background worker threads.
Q20. Implement a retry mechanism for failed asynchronous tasks
async function retryOperation(fn, retries = 3, delay = 1000) {
try {
return await fn();
} catch (error) {
if (retries <= 0) throw error;
await new Promise(res => setTimeout(res, delay));
return retryOperation(fn, retries - 1, delay * 2);
}
}Repeats failing asynchronous tasks with exponential backoff delays.
Q21. Implement custom API request validation middleware
function validateSchema(schema) {
return (req, res, next) => {
const { error } = schema.validate(req.body);
if (error) {
return res.status(400).json({ error: error.details[0].message });
}
next();
};
}Validates incoming HTTP request body data against predefined schemas before routing.
Q22. Implement simple in-memory session store
class MemoryStore {
constructor() {
this.sessions = new Map();
}
set(sessionId, data, ttl = 3600) {
const expiry = Date.now() + ttl * 1000;
this.sessions.set(sessionId, { data, expiry });
}
get(sessionId) {
const session = this.sessions.get(sessionId);
if (!session) return null;
if (Date.now() > session.expiry) {
this.sessions.delete(sessionId);
return null;
}
return session.data;
}
}Manages user session tokens and payloads in server RAM with expiration control.
Q23. Implement a custom JSON file database wrapper
const fs = require('fs');
class JsonDatabase {
constructor(filepath) {
this.filepath = filepath;
if (!fs.existsSync(this.filepath)) fs.writeFileSync(this.filepath, JSON.stringify({}));
}
read() {
return JSON.parse(fs.readFileSync(this.filepath, 'utf8'));
}
write(data) {
fs.writeFileSync(this.filepath, JSON.stringify(data, null, 2));
}
}Provides simple synchronous read/write storage operations over JSON files.
Q24. Implement environment variable validation utility
function validateEnv(requiredKeys) {
const missing = requiredKeys.filter(key => !process.env[key]);
if (missing.length > 0) {
console.error(`Missing required environment variables: ${missing.join(', ')}`);
process.exit(1);
}
}Ensures necessary configuration secrets exist before application bootstrapping.
Q25. Implement a simple HTTP Proxy server using http module
const http = require('http');
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});
const server = http.createServer((req, res) => {
proxy.web(req, res, { target: 'http://localhost:5000' }, (err) => {
res.writeHead(502, { 'Content-Type': 'text/plain' });
res.end('Bad Gateway');
});
});
server.listen(8080);Routes and forwards incoming HTTP traffic to target backend microservices.
Q26. Implement basic CORS configuration middleware
function cors(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
return res.sendStatus(204);
}
next();
}Injects standard Cross-Origin Resource Sharing headers into HTTP responses.
Q27. Implement a simple task queue processor
class TaskQueue {
constructor(concurrency = 2) {
this.concurrency = concurrency;
this.running = 0;
this.queue = [];
}
push(task) {
this.queue.push(task);
this.next();
}
next() {
if (this.running >= this.concurrency || this.queue.length === 0) return;
const task = this.queue.shift();
this.running++;
task().finally(() => {
this.running--;
this.next();
});
}
}Executes asynchronous tasks sequentially with strict concurrency limits.
Q28. Implement an asynchronous waterfall flow control utility
async function waterfall(tasks, initialArg) {
let res = initialArg;
for (const task of tasks) {
res = await task(res);
}
return res;
}Executes an array of async functions in sequence, passing output to the next.
Q29. Implement basic request logging middleware
function requestLogger(req, res, next) {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
console.log(`${req.method} ${req.originalUrl} ${res.statusCode} - ${duration}ms`);
});
next();
}Tracks HTTP method paths, response statuses, and execution durations.
Q30. Implement a secure password generator utility
const crypto = require('crypto');
function generateSecurePassword(length = 12) {
return crypto.randomBytes(Math.ceil(length / 2))
.toString('hex')
.slice(0, length);
}Produces cryptographically secure random password strings.
Q31. Implement an async memoization wrapper function
function memoizeAsync(fn) {
const cache = new Map();
return async function (...args) {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const result = await fn(...args);
cache.set(key, result);
return result;
};
}Caches resolution values of asynchronous functions based on arguments.
Q32. Implement file download HTTP streaming handler
const fs = require('fs');
function downloadFile(req, res, filePath) {
if (!fs.existsSync(filePath)) return res.status(404).send('File not found');
res.setHeader('Content-Disposition', 'attachment; filename="download.zip"');
res.setHeader('Content-Type', 'application/zip');
const stream = fs.createReadStream(filePath);
stream.pipe(res);
}Streams large file binaries directly to HTTP client download responses.
Q33. Implement basic token bucket rate limiter class
class TokenBucket {
constructor(capacity, fillRate) {
this.capacity = capacity;
this.tokens = capacity;
this.fillRate = fillRate;
this.lastFilled = Date.now();
}
consume() {
const now = Date.now();
const elapsed = (now - this.lastFilled) / 1000;
this.tokens = Math.min(this.capacity, this.tokens + elapsed * this.fillRate);
this.lastFilled = now;
if (this.tokens >= 1) {
this.tokens -= 1;
return true;
}
return false;
}
}Implements precise traffic shaping and token replenishment algorithms.
Q34. Implement a simple pagination helper utility
function paginate(array, page = 1, limit = 10) {
const offset = (page - 1) * limit;
const paginatedItems = array.slice(offset, offset + limit);
return {
page,
limit,
totalItems: array.length,
totalPages: Math.ceil(array.length / limit),
data: paginatedItems
};
}Slices array records into structured pagination responses.
Q35. Implement automatic server reload watcher simulation
const fs = require('fs');
function watchFileChanges(filePath, callback) {
fs.watch(filePath, (eventType, filename) => {
if (filename) {
callback(eventType, filename);
}
});
}Monitors file system modifications to trigger dynamic reloads.
Q36. Implement an async parallel mapper function
async function asyncMap(array, asyncFn) {
return Promise.all(array.map(item => asyncFn(item)));
}Executes asynchronous mapping callbacks concurrently across array elements.
Q37. Implement an async serial mapper function
async function asyncSerialMap(array, asyncFn) {
const results = [];
for (const item of array) {
results.push(await asyncFn(item));
}
return results;
}Executes asynchronous mapping callbacks one by one in serial order.
Q38. Implement a simple HMAC signature verifier
const crypto = require('crypto');
function verifyHmac(payload, secret, receivedSignature) {
const hash = crypto.createHmac('sha256', secret).update(payload).digest('hex');
return crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(receivedSignature));
}Verifies webhook or API payload signatures securely against timing attacks.
Q39. Implement an XML to JSON parser wrapper using xml2js
const xml2js = require('xml2js');
async function parseXmlToJson(xmlData) {
const parser = new xml2js.Parser({ explicitArray: false });
return await parser.parseStringPromise(xmlData);
}Parses XML string payloads into structured JavaScript JSON objects.
Q40. Implement simple gzip response compression middleware
const zlib = require('zlib');
function compressResponse(req, res, next) {
const acceptEncoding = req.headers['accept-encoding'] || '';
if (!acceptEncoding.includes('gzip')) return next();
// Custom gzip compression wrappers can be applied here
next();
}Optimizes HTTP response payload sizes using gzip compression headers.
Q41. Implement simple cookie parser middleware from scratch
function cookieParser(req, res, next) {
req.cookies = {};
const cookieHeader = req.headers.cookie;
if (cookieHeader) {
cookieHeader.split(';').forEach(cookie => {
const [name, ...rest] = cookie.split('=');
req.cookies[name.trim()] = decodeURIComponent(rest.join('='));
});
}
next();
}Parses raw HTTP cookie header strings into accessible request object properties.
Q42. Implement a simple query string parser utility
function parseQueryString(urlStr) {
const queryIndex = urlStr.indexOf('?');
if (queryIndex === -1) return {};
const queryString = urlStr.slice(queryIndex + 1);
const params = {};
queryString.split('&').forEach(param => {
const [key, value] = param.split('=');
if (key) params[decodeURIComponent(key)] = decodeURIComponent(value || '');
});
return params;
}Extracts URL parameter keys and values into structured associative objects.
Q43. Implement an async timeout wrapper for promises
async function promiseWithTimeout(promise, ms) {
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error('Operation timed out')), ms)
);
return Promise.race([promise, timeout]);
}Rejects asynchronous operations if they exceed specified duration thresholds.
Q44. Implement basic directory listing utility
const fs = require('fs');
function getDirectoryContents(dirPath) {
return fs.readdirSync(dirPath, { withFileTypes: true }).map(item => ({
name: item.name,
isDirectory: item.isDirectory()
}));
}Scans directories and returns file metadata flags.
Q45. Implement simple in-memory pub/sub message broker
class PubSub {
constructor() {
this.channels = {};
}
subscribe(channel, fn) {
if (!this.channels[channel]) this.channels[channel] = [];
this.channels[channel].push(fn);
}
publish(channel, data) {
if (this.channels[channel]) {
this.channels[channel].forEach(fn => fn(data));
}
}
}Facilitates decoupled publish-subscribe messaging across application components.
Q46. Implement custom sanitize HTML string utility
function sanitizeHtmlString(str) {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}Escapes special HTML characters to mitigate cross-site scripting vulnerabilities.
Q47. Implement random string generator utility
function generateRandomString(length = 10) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}Generates fixed-length random alphanumeric strings.
Q48. Implement basic HTTP request logger wrapper
const http = require('http');
function logIncomingRequest(req) {
console.log(`[${new Date().toISOString()}] ${req.method} request received at ${req.url}`);
}Logs essential metadata for incoming HTTP socket requests.
Q49. Implement a simple file search utility
const fs = require('fs');
const path = require('path');
function searchFile(dir, targetName) {
const files = fs.readdirSync(dir);
for (const file of files) {
const fullPath = path.join(dir, file);
if (fs.statSync(fullPath).isDirectory()) {
const found = searchFile(fullPath, targetName);
if (found) return found;
} else if (file === targetName) {
return fullPath;
}
}
return null;
}Recursively searches directory trees to locate target filenames.
Q50. Implement a simple semaphore lock mechanism
class Semaphore {
constructor(max) {
this.max = max;
this.count = 0;
this.waiting = [];
}
acquire() {
return new Promise(resolve => {
if (this.count < this.max) {
this.count++;
resolve();
} else {
this.waiting.push(resolve);
}
});
}
release() {
this.count--;
if (this.waiting.length > 0) {
this.count++;
const next = this.waiting.shift();
next();
}
}
}Restricts concurrent access to critical code sections using synchronization semaphores.
Q51. Implement a basic health check endpoint handler
function healthCheckHandler(req, res) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'UP', uptime: process.uptime(), timestamp: Date.now() }));
}Provides server heartbeat metrics for container load balancer probes.
Q52. Implement an asynchronous file copy utility
const fs = require('fs').promises;
async function copyFileAsync(src, dest) {
try {
await fs.copyFile(src, dest);
console.log('File copied successfully');
} catch (error) {
console.error('Copy failed:', error);
}
}Copies files asynchronously using Promise-based file system APIs.
Q53. Implement a simple URL validator helper
function isValidUrl(string) {
try {
const url = new URL(string);
return url.protocol === 'http:' || url.protocol === 'https:';
} catch (_) {
return false;
}
}Validates well-formed HTTP and HTTPS URL strings.
Q54. Implement a simple CSV line parser utility
function parseCsvLine(line) {
return line.split(',').map(item => item.trim().replace(/^"|"$/g, ''));
}Splits comma-separated CSV lines into cleaned array values.
Q55. Implement a basic response timer middleware
function responseTimer(req, res, next) {
const startHrTime = process.hrtime();
res.on('finish', () => {
const elapsedHrTime = process.hrtime(startHrTime);
const elapsedTimeInMs = elapsedHrTime[0] * 1000 + elapsedHrTime[1] / 1e6;
console.log(`Response time: ${elapsedTimeInMs.toFixed(3)} ms`);
});
next();
}Measures high-resolution request execution durations in milliseconds.
Q56. Implement an async sleep delay function
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// Usage: await sleep(2000);Provides clean Promise-based execution pauses.
Q57. Implement basic in-memory counter metrics collector
class MetricsCollector {
constructor() {
this.counters = new Map();
}
increment(metric) {
const current = this.counters.get(metric) || 0;
this.counters.set(metric, current + 1);
}
get(metric) {
return this.counters.get(metric) || 0;
}
}Collects lightweight in-memory application performance metrics.
Q58. Implement a simple query parameter normalizer middleware
function normalizeQuery(req, res, next) {
for (let key in req.query) {
if (typeof req.query[key] === 'string') {
req.query[key] = req.query[key].trim();
}
}
next();
}Sanitizes and trims whitespace from incoming request query parameters.
Q59. Implement a basic directory creation utility
const fs = require('fs');
function ensureDirectoryExists(dirPath) {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
}Creates directory hierarchies recursively if they do not exist.
Q60. Implement a simple JSON payload size limiter middleware
function jsonSizeLimiter(limitInBytes) {
return (req, res, next) => {
let size = 0;
req.on('data', chunk => {
size += chunk.length;
if (size > limitInBytes) {
res.status(413).send('Payload Too Large');
req.destroy();
}
});
next();
};
}Aborts requests exceeding maximum payload byte thresholds.
Q61. Implement basic IP address extractor helper
function getClientIp(req) {
return req.headers['x-forwarded-for'] || req.socket.remoteAddress;
}Retrieves client IP addresses considering proxy headers.
Q62. Implement a simple base64 encoder/decoder utility
function encodeBase64(str) {
return Buffer.from(str).toString('base64');
}
function decodeBase64(base64Str) {
return Buffer.from(base64Str, 'base64').toString('utf8');
}Converts strings to and from base64 encoding using Node Buffers.
Q63. Implement a simple static file server handler
const fs = require('fs');
const path = require('path');
function serveStaticFile(res, filePath) {
if (fs.existsSync(filePath)) {
const stream = fs.createReadStream(filePath);
stream.pipe(res);
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
}Serves static assets directly via readable file streams.
Q64. Implement basic input trimming middleware for forms
function trimBodyInputs(req, res, next) {
if (req.body && typeof req.body === 'object') {
for (let key in req.body) {
if (typeof req.body[key] === 'string') {
req.body[key] = req.body[key].trim();
}
}
}
next();
}Trims string properties in request bodies automatically.
Q65. Implement a simple object flatten utility
function flattenObject(obj, prefix = '') {
return Object.keys(obj).reduce((acc, k) => {
const pre = prefix.length ? prefix + '.' : '';
if (typeof obj[k] === 'object' && obj[k] !== null && !Array.isArray(obj[k])) {
Object.assign(acc, flattenObject(obj[k], pre + k));
} else {
acc[pre + k] = obj[k];
}
return acc;
}, {});
}Flattens nested multi-level objects into dot-notation single-level objects.
Q66. Implement a simple array chunking utility
function chunkArray(array, size) {
const chunked = [];
for (let i = 0; i < array.length; i += size) {
chunked.push(array.slice(i, i + size));
}
return chunked;
}Splits large arrays into smaller fixed-size sub-arrays.
Q67. Implement a simple array unique elements filter
function uniqueArray(array) {
return [...new Set(array)];
}Removes duplicate values from arrays using ES6 Sets.
Q68. Implement a basic UUID v4 generator simulation
function generateUuidV4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}Generates pseudo-random RFC4122 version 4 UUID strings.
Q69. Implement a simple object omit keys utility
function omitKeys(obj, keys) {
const clone = { ...obj };
keys.forEach(key => delete clone[key]);
return clone;
}Removes specified keys from target JavaScript objects.
Q70. Implement a simple object pick keys utility
function pickKeys(obj, keys) {
return keys.reduce((acc, key) => {
if (key in obj) acc[key] = obj[key];
return acc;
}, {});
}Extracts only desired property keys from objects.
Q71. Implement a basic query string builder utility
function buildQueryString(params) {
return Object.keys(params)
.map(key => encodeURIComponent(key) + '=' + encodeURIComponent(params[key]))
.join('&');
}Serializes object maps into URL-encoded query strings.
Q72. Implement a simple array intersection utility
function arrayIntersection(arr1, arr2) {
const set2 = new Set(arr2);
return arr1.filter(item => set2.has(item));
}Finds common elements shared between two arrays.
Q73. Implement a simple array difference utility
function arrayDifference(arr1, arr2) {
const set2 = new Set(arr2);
return arr1.filter(item => !set2.has(item));
}Returns elements present in the first array but absent in the second.
Q74. Implement a basic string truncation utility
function truncateString(str, limit) {
return str.length > limit ? str.slice(0, limit) + '...' : str;
}Shortens long strings and appends ellipsis markers.
Q75. Implement a simple camelCase converter utility
function toCamelCase(str) {
return str.replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : '');
}Converts dashed or snake-case strings into camelCase.
Q76. Implement a simple snake_case converter utility
function toSnakeCase(str) {
return str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.toLowerCase())
.join('_');
}Transforms camelCase strings into snake_case.
Q77. Implement a basic markdown bold stripper utility
function stripMarkdownBold(text) {
return text.replace(/\*\*(.*?)\*\*/g, '$1');
}Removes markdown bold syntax markers from text strings.
Q78. Implement a simple number range validator helper
function isBetween(num, min, max) {
return num >= min && num <= max;
}Verifies if numeric values fall within inclusive bounds.
Q79. Implement a basic async queue runner class
class AsyncQueue {
constructor(worker) {
this.worker = worker;
this.queue = [];
this.processing = false;
}
push(item) {
this.queue.push(item);
this.process();
}
async process() {
if (this.processing || this.queue.length === 0) return;
this.processing = true;
const item = this.queue.shift();
try {
await this.worker(item);
} catch (e) {
console.error(e);
}
this.processing = false;
this.process();
}
}Processes queued asynchronous task items serially.
Q80. Implement a simple file existence checker utility
const fs = require('fs');
async function fileExists(filePath) {
try {
await fs.promises.access(filePath);
return true;
} catch {
return false;
}
}Checks if files exist asynchronously using fs access permissions.
Q81. Implement a basic memory usage logger utility
function logMemoryUsage() {
const used = process.memoryUsage();
for (let key in used) {
console.log(`${key}: ${Math.round(used[key] / 1024 / 1024 * 100) / 100} MB`);
}
}Outputs current V8 heap and RSS memory consumption metrics.
Q82. Implement a simple URL pathname extractor utility
function getPathname(urlStr) {
try {
return new URL(urlStr).pathname;
} catch {
return '';
}
}Extracts URL path segments safely using URL APIs.
Q83. Implement a basic domain extractor helper
function extractDomain(urlStr) {
try {
return new URL(urlStr).hostname;
} catch {
return '';
}
}Retrieves host domains from complete URL strings.
Q84. Implement a simple async sequential runner function
async function runSequential(fns) {
for (const fn of fns) {
await fn();
}
}Executes arrays of asynchronous function callbacks one after another.
Q85. Implement a basic object property merger utility
function mergeObjects(target, source) {
for (let key of Object.keys(source)) {
if (source[key] instanceof Object && key in target) {
Object.assign(source[key], mergeObjects(target[key], source[key]));
}
}
return Object.assign(target || {}, source);
}Deep merges properties across source and target objects.
Q86. Implement a simple array partition utility
function partitionArray(array, isValid) {
return array.reduce((acc, elem) => {
acc[isValid(elem) ? 0 : 1].push(elem);
return acc;
}, [[], []]);
}Splits arrays into two groups based on truthy filter tests.
Q87. Implement a basic string masking utility
function maskString(str, visibleCount = 4) {
if (str.length <= visibleCount) return str;
return '*'.repeat(str.length - visibleCount) + str.slice(-visibleCount);
}Masks leading characters while keeping trailing characters visible.
Q88. Implement a simple file deletion wrapper
const fs = require('fs').promises;
async function deleteFileAsync(filePath) {
try {
await fs.unlink(filePath);
return true;
} catch {
return false;
}
}Deletes target files asynchronously with error trapping.
Q89. Implement a basic integer validator helper
function isInteger(value) {
return typeof value === 'number' && Number.isInteger(value);
}Validates strict integer number types.
Q90. Implement a simple alphanumeric validator helper
function isAlphanumeric(str) {
return /^[a-zA-Z0-9]+$/.test(str);
}Checks if strings contain solely letters and numbers.
Q91. Implement a basic email format checker helper
function isValidEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}Performs standard regex checks for valid email structures.
Q92. Implement a simple array shuffle utility
function shuffleArray(array) {
const arr = [...array];
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}Randomizes array element ordering using Fisher-Yates shuffle algorithms.
Q93. Implement a basic array sample selector helper
function getRandomSample(array) {
return array[Math.floor(Math.random() * array.length)];
}Pulls random elements from array collections.
Q94. Implement a basic text word counter utility
function countWords(str) {
return str.trim().split(/\s+/).filter(Boolean).length;
}Tallies word counts across text strings.
Q95. Implement a simple camelCase to title case helper
function camelToTitle(str) {
const result = str.replace(/([A-Z])/g, ' $1');
return result.charAt(0).toUpperCase() + result.slice(1);
}Converts camelCase keys into human-readable title case.
Q96. Implement a basic JSON stringifier safe wrapper
function safeJsonStringify(obj) {
try {
return JSON.stringify(obj);
} catch {
return '{}';
}
}Serializes objects into JSON strings safely catching circular reference errors.
Q97. Implement a basic JSON parser safe wrapper
function safeJsonParse(str, fallback = {}) {
try {
return JSON.parse(str);
} catch {
return fallback;
}
}Parses JSON strings safely with fallback object returns on syntax errors.
Q98. Implement a basic number formatter helper with commas
function formatNumber(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}Formats large numbers with comma separator groupings.
Q99. Implement a basic execution time benchmark wrapper
async function benchmark(fn) {
const start = performance.now();
await fn();
const end = performance.now();
console.log(`Execution time: ${(end - start).toFixed(3)} ms`);
}Measures precise function execution durations using high-res timers.
Q100. Implement a basic application cluster fork supervisor
const cluster = require('cluster');
function startClusterWorker(workerScript) {
if (cluster.isPrimary) {
cluster.fork();
cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} exited. Restarting...`);
cluster.fork();
});
} else {
require(workerScript);
}
}Supervises worker processes and restarts them automatically upon unexpected exits.
Q101. Implement custom HTTP GET request helper using http module
const http = require('http');
function httpGet(url) {
return new Promise((resolve, reject) => {
http.get(url, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => resolve(data));
}).on('error', reject);
});
}Performs native HTTP GET requests returning response promises.
Q102. Implement custom HTTP POST request helper using http module
const http = require('http');
function httpPost(url, payload) {
return new Promise((resolve, reject) => {
const data = JSON.stringify(payload);
const urlObj = new URL(url);
const options = {
hostname: urlObj.hostname,
port: urlObj.port,
path: urlObj.pathname,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)
}
};
const req = http.request(options, (res) => {
let responseData = '';
res.on('data', chunk => responseData += chunk);
res.on('end', () => resolve(responseData));
});
req.on('error', reject);
req.write(data);
req.end();
});
}Sends JSON payloads via native HTTP POST request streams.
Q103. Implement simple EventEmitter once listener helper
function once(emitter, event) {
return new Promise((resolve) => {
const listener = (...args) => {
emitter.off(event, listener);
resolve(args);
};
emitter.on(event, listener);
});
}Converts single-emission events into Promise resolutions.
Q104. Implement a basic recursive file finder helper
const fs = require('fs');
const path = require('path');
function walkDir(dir, callback) {
fs.readdirSync(dir).forEach(f => {
const dirPath = path.join(dir, f);
if (fs.statSync(dirPath).isDirectory()) {
walkDir(dirPath, callback);
} else {
callback(dirPath);
}
});
}Traverses directory trees recursively executing callbacks per file.
Q105. Implement simple in-memory LRU cache eviction policy class
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = new Map();
}
get(key) {
if (!this.cache.has(key)) return -1;
const val = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, val);
return val;
}
put(key, value) {
if (this.cache.has(key)) this.cache.delete(key);
else if (this.cache.size >= this.capacity) {
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(key, value);
}
}Evicts least recently used cache entries upon reaching capacity limits.
Q106. Implement basic process signal event listener setup
function setupProcessListeners() {
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
process.exit(1);
});
}Captures unhandled synchronous exceptions and asynchronous promise rejections.
Q107. Implement simple environment configuration loader helper
const fs = require('fs');
const path = require('path');
function loadSimpleEnv(filePath = '.env') {
if (!fs.existsSync(filePath)) return;
const lines = fs.readFileSync(filePath, 'utf8').split('\n');
lines.forEach(line => {
const parts = line.split('=');
if (parts.length === 2) {
process.env[parts[0].trim()] = parts[1].trim();
}
});
}Parses key-value .env configuration files into process.env variables.
Q108. Implement basic buffer hex string converter utility
function bufferToHex(buffer) {
return buffer.toString('hex');
}
function hexToBuffer(hexStr) {
return Buffer.from(hexStr, 'hex');
}Encodes and decodes raw Node buffers into hexadecimal strings.
Q109. Implement simple directory size calculator utility
const fs = require('fs');
const path = require('path');
function getDirectorySize(dirPath) {
let size = 0;
const files = fs.readdirSync(dirPath);
files.forEach(file => {
const filePath = path.join(dirPath, file);
const stats = fs.statSync(filePath);
if (stats.isDirectory()) {
size += getDirectorySize(filePath);
} else {
size += stats.size;
}
});
return size;
}Recursively aggregates total file storage byte sizes across directory trees.
Q110. Implement basic stream text transformer uppercase wrapper
const { Transform } = require('stream');
class UppercaseTransform extends Transform {
_transform(chunk, encoding, callback) {
this.push(chunk.toString().toUpperCase());
callback();
}
}Transforms incoming stream text buffers into uppercase chunks.
Q111. Implement simple crypto SHA-256 hasher utility
const crypto = require('crypto');
function sha256Hash(text) {
return crypto.createHash('sha256').update(text).digest('hex');
}Computes cryptographic SHA-256 checksum hashes.
Q112. Implement basic URL query parameter appender helper
function appendQueryParam(baseUrl, key, value) {
const url = new URL(baseUrl);
url.searchParams.append(key, value);
return url.toString();
}Appends query parameters securely onto existing URL strings.
Q113. Implement simple array chunk processing pipeline
async function processInChunks(array, chunkSize, asyncTask) {
for (let i = 0; i < array.length; i += chunkSize) {
const chunk = array.slice(i, i + chunkSize);
await Promise.all(chunk.map(item => asyncTask(item)));
}
}Processes large array collections in controlled concurrent batches.
Q114. Implement basic cookie serializer utility
function serializeCookie(name, val, options = {}) {
let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(val)}`;
if (options.maxAge) cookie += `; Max-Age=${options.maxAge}`;
if (options.path) cookie += `; Path=${options.path}`;
if (options.domain) cookie += `; Domain=${options.domain}`;
if (options.secure) cookie += '; Secure';
if (options.httpOnly) cookie += '; HttpOnly';
return cookie;
}Serializes cookie property attributes into valid HTTP header strings.
Q115. Implement simple HTTP header sanitizer helper
function sanitizeHeaders(headers) {
const sanitized = { ...headers };
delete sanitized['x-powered-by'];
delete sanitized['server'];
return sanitized;
}Removes server fingerprinting headers to improve security posture.
Q116. Implement basic JSON file atomic writer utility
const fs = require('fs');
function writeJsonAtomic(filePath, data) {
const tempPath = filePath + '.tmp';
fs.writeFileSync(tempPath, JSON.stringify(data, null, 2));
fs.renameSync(tempPath, filePath);
}Writes JSON data atomically using temporary files and atomic renames.
Q117. Implement simple async pool concurrency limiter class
class AsyncPool {
constructor(limit) {
this.limit = limit;
this.running = 0;
this.queue = [];
}
async add(fn) {
if (this.running >= this.limit) {
await new Promise(resolve => this.queue.push(resolve));
}
this.running++;
try {
return await fn();
} finally {
this.running--;
if (this.queue.length > 0) {
const next = this.queue.shift();
next();
}
}
}
}Limits maximum concurrent asynchronous task executions.
Q118. Implement basic file stream line counter utility
const fs = require('fs');
function countFileLines(filePath) {
return new Promise((resolve, reject) => {
let count = 0;
fs.createReadStream(filePath)
.on('data', chunk => {
for (let i = 0; i < chunk.length; ++i) {
if (chunk[i] === 10) count++;
}
})
.on('end', () => resolve(count))
.on('error', reject);
});
}Counts total newline characters in files efficiently via read streams.
Q119. Implement simple random integer generator helper
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}Generates random integers within inclusive ranges.
Q120. Implement basic string slugifier utility
function slugify(text) {
return text.toString().toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^\w\-]+/g, '')
.replace(/\-\-+/g, '-')
.replace(/^-+/, '')
.replace(/-+$/, '');
}Converts raw text titles into clean URL slug formats.
Q121. Implement simple process arguments parser helper
function parseArgs() {
const args = {};
process.argv.slice(2).forEach(arg => {
const [key, value] = arg.split('=');
if (key && value) {
args[key.replace(/^--/, '')] = value;
}
});
return args;
}Parses command-line script arguments into structured maps.
Q122. Implement basic UTC timestamp string generator
function getUtcTimestamp() {
return new Date().toISOString();
}Generates ISO format UTC timestamp strings.
Q123. Implement simple object key case transformer utility
function transformObjectKeys(obj, transformFn) {
return Object.keys(obj).reduce((acc, key) => {
acc[transformFn(key)] = obj[key];
return acc;
}, {});
}Transforms all top-level keys in objects using custom casing functions.
Q124. Implement basic array chunked flattener helper
function flattenDeep(arr) {
return arr.reduce((acc, val) =>
Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []
);
}Recursively flattens multi-dimensional nested arrays.
Q125. Implement simple base64 URL-safe encoder/decoder
function base64UrlEncode(str) {
return Buffer.from(str).toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
}
function base64UrlDecode(str) {
str = str.replace(/-/g, '+').replace(/_/g, '/');
while (str.length % 4) str += '=';
return Buffer.from(str, 'base64').toString('utf8');
}Encodes and decodes URL-safe base64 strings used in JWT tokens.
Q126. Implement basic HTTP server keep-alive configuration
const http = require('http');
const server = http.createServer((req, res) => {
res.end('OK');
});
server.keepAliveTimeout = 65000;
server.headersTimeout = 66000;Configures explicit HTTP keep-alive timeouts for persistent socket connections.
Q127. Implement simple stream object mode counter transformer
const { Transform } = require('stream');
class CounterTransform extends Transform {
constructor() {
super({ objectMode: true });
this.count = 0;
}
_transform(chunk, encoding, callback) {
this.count++;
this.push({ count: this.count, data: chunk });
callback();
}
}Transforms object mode streams appending sequential count metadata.
Q128. Implement basic OS CPU architecture detector helper
const os = require('os');
function getSystemInfo() {
return {
platform: os.platform(),
arch: os.arch(),
cpus: os.cpus().length,
freeMemory: os.freemem(),
totalMemory: os.totalmem()
};
}Retrieves operating system hardware metrics via OS module.
Q129. Implement basic async function wrapper with automatic try/catch
function asyncHandler(fn) {
return function (req, res, next) {
Promise.resolve(fn(req, res, next)).catch(next);
};
}Catches asynchronous route errors automatically without explicit try/catch blocks.
Q130. Implement simple password complexity validator regex helper
function checkPasswordStrength(password) {
const hasUpper = /[A-Z]/.test(password);
const hasLower = /[a-z]/.test(password);
const hasNum = /[0-9]/.test(password);
const hasSpecial = /[^A-Za-z0-9]/.test(password);
const isLongEnough = password.length >= 8;
return hasUpper && hasLower && hasNum && hasSpecial && isLongEnough;
}Validates complex password security criteria.
Q131. Implement basic file permissions checker helper
const fs = require('fs');
function checkFilePermissions(filePath) {
try {
fs.accessSync(filePath, fs.constants.R_OK | fs.constants.W_OK);
return { readable: true, writable: true };
} catch {
return { readable: false, writable: false };
}
}Verifies read and write file permission flags synchronously.
Q132. Implement simple express middleware conditional wrapper
function conditionalMiddleware(conditionFn, middleware) {
return function (req, res, next) {
if (conditionFn(req)) {
return middleware(req, res, next);
}
next();
};
}Executes express middleware conditionally based on request state.
Q133. Implement basic array group by utility function
function groupBy(array, keyFn) {
return array.reduce((result, item) => {
const key = typeof keyFn === 'function' ? keyFn(item) : item[keyFn];
if (!result[key]) result[key] = [];
result[key].push(item);
return result;
}, {});
}Groups array objects into associative key buckets.
Q134. Implement basic array frequency counter utility
function countFrequencies(array) {
return array.reduce((acc, val) => {
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});
}Counts occurrence frequencies of items in collections.
Q135. Implement basic timer promise wrapper helper
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}Wraps setTimeout into a clean async Promise.
Q136. Implement basic hex color validator helper
function isValidHexColor(hex) {
return /^#([0-9A-F]{3}){1,2}$/i.test(hex);
}Validates standard CSS hexadecimal color strings.
Q137. Implement basic MIME type lookup helper
function getMimeType(filePath) {
const ext = filePath.split('.').pop().toLowerCase();
const map = {
html: 'text/html',
css: 'text/css',
js: 'application/javascript',
json: 'application/json',
png: 'image/png',
jpg: 'image/jpeg'
};
return map[ext] || 'application/octet-stream';
}Resolves standard file extension MIME types.
Q138. Implement basic object value mapper utility
function mapObjectValues(obj, fn) {
return Object.keys(obj).reduce((acc, key) => {
acc[key] = fn(obj[key], key);
return acc;
}, {});
}Maps values across object properties preserving keys.
Q139. Implement basic array index finder predicate helper
function findLastIndex(array, predicate) {
for (let i = array.length - 1; i >= 0; i--) {
if (predicate(array[i], i, array)) return i;
}
return -1;
}Finds the last array index matching predicate conditions.
Q140. Implement basic string capitalizer helper
function capitalize(str) {
if (!str) return '';
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}Capitalizes the first character of strings.
Q141. Implement basic process title setter helper
function setProcessTitle(title) {
process.title = title;
console.log(`Process title set to: ${process.title}`);
}Sets active process titles visible in system monitor tools.
Q142. Implement basic array element frequency sorter
function sortByFrequency(array) {
const freq = countFrequencies(array);
return [...array].sort((a, b) => freq[b] - freq[a]);
}Sorts array elements based on occurrence frequency counts.
Q143. Implement basic object keys filter helper
function filterObjectKeys(obj, predicate) {
return Object.keys(obj)
.filter(key => predicate(key, obj[key]))
.reduce((acc, key) => {
acc[key] = obj[key];
return acc;
}, {});
}Filters object key-value pairs matching predicate conditions.
Q144. Implement basic array range generator helper
function range(start, end, step = 1) {
const result = [];
for (let i = start; i <= end; i += step) {
result.push(i);
}
return result;
}Generates numeric sequence arrays within range bounds.
Q145. Implement basic string reverse helper
function reverseString(str) {
return str.split('').reverse().join('');
}Reverses character sequence strings.
Q146. Implement basic palindrome checker helper
function isPalindrome(str) {
const clean = str.replace(/[^A-Za-z0-9]/g, '').toLowerCase();
return clean === clean.split('').reverse().join('');
}Checks if strings read the same forwards and backwards.
Q147. Implement basic factorial calculator helper
function factorial(n) {
if (n < 0) return -1;
let res = 1;
for (let i = 2; i <= n; i++) res *= i;
return res;
}Calculates mathematical factorial numbers.
Q148. Implement basic fibonacci sequence generator helper
function fibonacci(n) {
const fib = [0, 1];
for (let i = 2; i < n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib.slice(0, n);
}Generates Fibonacci numerical sequences.
Q149. Implement basic prime number checker helper
function isPrimeNumber(num) {
if (num <= 1) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}Verifies if numbers are prime efficiently.
Q150. Implement basic temperature converter helper
function celsiusToFahrenheit(c) {
return (c * 9/5) + 32;
}
function fahrenheitToCelsius(f) {
return (f - 32) * 5/9;
}Converts temperature units between Celsius and Fahrenheit.
Q151. Implement basic file line writer helper
const fs = require('fs');
function appendLineToFile(filePath, line) {
fs.appendFileSync(filePath, line + '\n', 'utf8');
}Appends single text lines to files synchronously.
Q152. Implement basic environment mode checker helper
function isProduction() {
return process.env.NODE_ENV === 'production';
}Checks if the current runtime environment is production.
Q153. Implement basic empty object checker helper
function isEmptyObject(obj) {
return obj && Object.keys(obj).length === 0 && obj.constructor === Object;
}Determines if objects contain zero enumerable properties.
Q154. Implement basic array element swapper helper
function swapArrayElements(arr, index1, index2) {
const temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
return arr;
}Swaps positions of two array elements.
Q155. Implement basic string word replacer helper
function replaceWords(str, mapObj) {
const re = new RegExp(Object.keys(mapObj).join("|"), "gi");
return str.replace(re, matched => mapObj[matched]);
}Replaces multiple distinct words using mapping dictionaries.
Q156. Implement basic RGB to HEX color converter
function rgbToHex(r, g, b) {
return "#" + [r, g, b].map(x => {
const hex = x.toString(16);
return hex.length === 1 ? "0" + hex : hex;
}).join("");
}Converts RGB numerical color values into hexadecimal strings.
Q157. Implement basic HEX to RGB color converter
function hexToRgb(hex) {
let c = hex.replace('#', '');
if (c.length === 3) c = c.split('').map(x => x + x).join('');
const num = parseInt(c, 16);
return { r: num >> 16, g: (num >> 8) & 255, b: num & 255 };
}Converts hexadecimal color codes into RGB coordinate objects.
Q158. Implement basic file extension extractor helper
const path = require('path');
function getFileExtension(filename) {
return path.extname(filename);
}Extracts file extension strings from filename paths.
Q159. Implement basic time duration formatter helper
function formatDuration(ms) {
const seconds = Math.floor((ms / 1000) % 60);
const minutes = Math.floor((ms / (1000 * 60)) % 60);
const hours = Math.floor(ms / (1000 * 60 * 60));
return `${hours}h ${minutes}m ${seconds}s`;
}Formats millisecond durations into human-readable hours, minutes, and seconds.
Q160. Implement basic query parameter remover helper
function removeQueryParam(urlStr, param) {
const url = new URL(urlStr);
url.searchParams.delete(param);
return url.toString();
}Deletes specific query parameters from URL strings.
Q161. Implement basic array flattening depth utility
function flattenDepth(arr, depth = 1) {
return depth > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flattenDepth(val, depth - 1) : val), []) : arr.slice();
}Flattens nested arrays up to specified recursion depths.
Q162. Implement basic object deep freezing helper
function deepFreeze(obj) {
Object.getOwnPropertyNames(obj).forEach(name => {
const prop = obj[name];
if (prop && (typeof prop === 'object' || typeof prop === 'function')) {
deepFreeze(prop);
}
});
return Object.freeze(obj);
}Freezes objects recursively preventing any property mutations.
Q163. Implement basic string character frequency counter
function characterFrequency(str) {
const freq = {};
for (let char of str) {
freq[char] = (freq[char] || 0) + 1;
}
return freq;
}Counts character occurrence frequencies in text strings.
Q164. Implement basic array element frequency filter
function filterByMinFrequency(arr, minFreq) {
const freq = countFrequencies(arr);
return arr.filter(item => freq[item] >= minFreq);
}Filters array elements meeting minimum frequency thresholds.
Q165. Implement basic string prefix stripper helper
function stripPrefix(str, prefix) {
return str.startsWith(prefix) ? str.slice(prefix.length) : str;
}Strips matching prefix substrings from string beginnings.
Q166. Implement basic string suffix stripper helper
function stripSuffix(str, suffix) {
return str.endsWith(suffix) ? str.slice(0, -suffix.length) : str;
}Strips matching suffix substrings from string endings.
Q167. Implement basic array chunk processor class
class ChunkProcessor {
constructor(chunkSize) {
this.chunkSize = chunkSize;
}
*process(array) {
for (let i = 0; i < array.length; i += this.chunkSize) {
yield array.slice(i, i + this.chunkSize);
}
}
}Yields array chunks lazily using generator functions.
Q168. Implement basic async retry wrapper with condition
async function retryCondition(fn, conditionFn, retries = 3) {
try {
const res = await fn();
if (conditionFn(res) && retries > 0) {
return retryCondition(fn, conditionFn, retries - 1);
}
return res;
} catch (err) {
if (retries > 0) return retryCondition(fn, conditionFn, retries - 1);
throw err;
}
}Retries async operations conditionally based on result payloads.
Q169. Implement basic object key sorter helper
function sortObjectKeys(obj) {
return Object.keys(obj).sort().reduce((acc, key) => {
acc[key] = obj[key];
return acc;
}, {});
}Sorts object keys alphabetically.
Q170. Implement basic array element frequency ranker
function rankByFrequency(arr) {
const freq = countFrequencies(arr);
return Object.keys(freq).sort((a, b) => freq[b] - freq[a]);
}Ranks unique array elements descending by frequency.
Q171. Implement basic URL parameter extractor helper
function getUrlParams(urlStr) {
const url = new URL(urlStr);
const params = {};
url.searchParams.forEach((value, key) => {
params[key] = value;
});
return params;
}Extracts query parameters into clean object maps using URL APIs.
Q172. Implement basic number rounder to decimal places helper
function roundTo(num, decimals = 2) {
return Number(Math.round(num + 'e' + decimals) + 'e-' + decimals);
}Rounds floating point numbers to precise decimal places.
Q173. Implement basic string ASCII code converter helper
function getAsciiCodes(str) {
return str.split('').map(char => char.charCodeAt(0));
}Converts strings into arrays of ASCII character codes.
Q174. Implement basic object property rename helper
function renameKey(obj, oldKey, newKey) {
if (oldKey in obj) {
obj[newKey] = obj[oldKey];
delete obj[oldKey];
}
return obj;
}Renames target keys in JavaScript objects.
Q175. Implement basic array moving average calculator
function movingAverage(arr, n) {
return arr.map((val, idx, arr) => {
const start = Math.max(0, idx - n + 1);
const subset = arr.slice(start, idx + 1);
const sum = subset.reduce((a, b) => a + b, 0);
return sum / subset.length;
});
}Calculates rolling window moving averages over numeric arrays.
Q176. Implement basic async pipeline composer helper
function asyncPipe(...fns) {
return async function(initialValue) {
let result = initialValue;
for (const fn of fns) {
result = await fn(result);
}
return result;
};
}Composes multiple async functions passing results sequentially.
Q177. Implement basic string acronym generator helper
function generateAcronym(str) {
return str.split(/\s+/).map(word => word.charAt(0).toUpperCase()).join('');
}Generates capital letter acronyms from phrase words.
Q178. Implement basic array chunk validator helper
function allChunksValid(arr, size, predicate) {
const chunks = chunkArray(arr, size);
return chunks.every(chunk => predicate(chunk));
}Validates if all array chunks satisfy predicate rules.
Q179. Implement basic number range overlap checker helper
function rangesOverlap(range1, range2) {
return Math.max(range1[0], range2[0]) <= Math.min(range1[1], range2[1]);
}Checks if two numeric range intervals overlap.
Q180. Implement basic object default value injector helper
function applyDefaults(defaults, options) {
return { ...defaults, ...options };
}Merges option objects over default configuration maps.
Q181. Implement basic string title case formatter
function toTitleCase(str) {
return str.replace(/\w\S*/g, txt => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());
}Formats strings into proper title case capitalization.
Q182. Implement basic array zip utility helper
function zipArrays(...arrays) {
const maxLength = Math.max(...arrays.map(arr => arr.length));
return Array.from({ length: maxLength }).map((_, i) => arrays.map(arr => arr[i]));
}Zips multiple arrays together into paired tuple collections.
Q183. Implement basic object property existence deep checker
function hasNestedPath(obj, path) {
return path.split('.').reduce((acc, key) => (acc && acc[key] !== undefined) ? acc[key] : undefined, obj) !== undefined;
}Checks if nested dot-notation property paths exist in objects.
Q184. Implement basic array subset checker helper
function isSubset(subset, parentSet) {
const parent = new Set(parentSet);
return subset.every(item => parent.has(item));
}Verifies if arrays are subsets of parent collections.
Q185. Implement basic string line splitter helper
function splitLines(str) {
return str.split(/\r?\n/);
}Splits multiline strings into individual line arrays.
Q186. Implement basic number percentage calculator helper
function calculatePercentage(partial, total) {
if (total === 0) return 0;
return (partial / total) * 100;
}Calculates ratio percentages between partial and total numbers.
Q187. Implement basic array mode statistic calculator
function getMode(arr) {
const freq = countFrequencies(arr);
let maxFreq = 0;
let modes = [];
for (let key in freq) {
if (freq[key] > maxFreq) {
maxFreq = freq[key];
modes = [key];
} else if (freq[key] === maxFreq) {
modes.push(key);
}
}
return modes;
}Calculates statistical mode values for datasets.
Q188. Implement basic object values sum calculator
function sumObjectValues(obj) {
return Object.values(obj).reduce((sum, val) => sum + (typeof val === 'number' ? val : 0), 0);
}Sums all numeric property values in objects.
Q189. Implement basic string whitespace normalizer helper
function normalizeWhitespace(str) {
return str.replace(/\s+/g, ' ').trim();
}Collapses multiple consecutive whitespace characters into single spaces.
Q190. Implement basic array median statistic calculator
function calculateMedian(arr) {
const sorted = [...arr].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2 !== 0 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
}Calculates statistical median values for numeric arrays.
Q191. Implement basic object key-value swapper helper
function invertObject(obj) {
return Object.keys(obj).reduce((acc, key) => {
acc[obj[key]] = key;
return acc;
}, {});
}Swaps keys and values across object property maps.
Q192. Implement basic array element frequency counter helper
function getFrequencyMap(arr) {
return countFrequencies(arr);
}Generates frequency maps for array elements.
Q193. Implement basic number sign checker helper
function getSign(num) {
return num > 0 ? 1 : num < 0 ? -1 : 0;
}Returns positive 1, negative -1, or zero based on number signs.
Q194. Implement basic string substring frequency counter
function countSubstringOccurrences(str, subStr) {
if (subStr === '') return 0;
let count = 0, pos = 0;
while ((pos = str.indexOf(subStr, pos)) !== -1) {
count++;
pos += subStr.length;
}
return count;
}Counts how many times substrings appear within parent strings.
Q195. Implement basic object pick by predicate helper
function pickBy(obj, predicate) {
return Object.keys(obj)
.filter(key => predicate(obj[key], key))
.reduce((acc, key) => {
acc[key] = obj[key];
return acc;
}, {});
}Picks object properties satisfying custom predicate testing functions.
Q196. Implement basic array chunk intersection helper
function chunkIntersection(arr1, arr2) {
return arrayIntersection(arr1, arr2);
}Finds intersections between array collections.
Q197. Implement basic string word reverse helper
function reverseWords(str) {
return str.trim().split(/\s+/).reverse().join(' ');
}Reverses the order of words in sentences.
Q198. Implement basic number clamp helper
function clamp(num, min, max) {
return Math.min(Math.max(num, min), max);
}Clamps numeric values within inclusive minimum and maximum limits.
Q199. Implement basic object deep property getter helper
function getNestedValue(obj, path, fallback = undefined) {
const travel = regexp =>
String.prototype.split
.call(path, regexp)
.filter(Boolean)
.reduce((res, key) => (res !== null && res !== undefined ? res[key] : res), obj);
const result = travel(/[,[\]]+?/);
return result === undefined || result === obj ? fallback : result;
}Retrieves deeply nested object properties via dot path strings safely.
Q200. Implement professional Node.js production HTTP server bootstrap template
const http = require('http');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'application/json');
res.statusCode = 200;
res.end(JSON.stringify({ message: 'Welcome to jsonbody.com enterprise Node.js API cluster' }));
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Enterprise server listening on port ${PORT}`);
});Provides robust production-ready HTTP server bootstrap initialization.