5 Javascript coding interview questions - Part 6
Q1. Flatten a Nested Object
Write a function that takes a nested object and flattens it into a single-level object with dot-separated keys.
Ans:
function flattenObject(obj, parent = '', res = {}){
for(let key in obj){
let newKey = parent ? `${parent}.${key}` : key;
if(typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])){
flattenObject(obj[key], newKey, res);
}
else{
res[newKey] = obj[key];
}
}
return res;
}
// Example
const input = { a: 1, b: { c: 2, d: { e: 3 } } };
console.log(flattenObject(input));
// { a: 1, "b.c": 2, "b.d.e": 3 }
Q2. Debounce Function
Implement a debounce function to delay execution until after a pause in calls.
Ans:
function debounce(fn, delay){
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(this, args), delay);
};
}
// Example
const log = debounce(() => console.log("Debounced!"), 1000);
log();
log();
log(); // Only runs once after 1s
Q3. Throttle Function
Implement a throttle function to limit execution of a function to once every X milliseconds.
Ans:
function throttle(fn, limit) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
fn.apply(this, args);
}
};
}
// Example
const log = throttle(() => console.log("Throttled!"), 2000);
setInterval(log, 500); // Runs every 2s, not every 0.5s
Q4. Group Anagrams
Given an array of strings, group words that are anagrams of each other.
Ans:
function groupAnagrams(words) {
const map = {};
for (let word of words) {
const key = word.split('').sort().join('');
if (!map[key]) map[key] = [];
map[key].push(word);
}
return Object.values(map);
}
// Example
console.log(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]));
// [["eat","tea","ate"], ["tan","nat"], ["bat"]]
Q5. Currying Function
Implement a function that transforms a normal function into a curried one.
Ans:
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
} else {
return function (...nextArgs) {
return curried.apply(this, args.concat(nextArgs));
};
}
};
}
// Example
function add(a, b, c) {
return a + b + c;
}
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)(3)); // 6
console.log(curriedAdd(1, 2)(3)); // 6
Top comments (0)