π‘ Topics they asked me & my solutions:
** Note: This is exactly the answers that I provided during the interview. **
β
What is a closure?
const counter = () => { let count = 0; const inner = () => { count++; return count } count = 2; return inner; } const c = counter(); console.log(c()); // 3
β
Predict setTimeout output
for (var i = 0; i < 3; i++) { setTimeout(function log() { console.log(i); }, 1000); }
β
Implement currying for sum
const sum = (arg) => { let total = 0; const inner = (n) => { if (n) { total += n; return inner; } else { return total; } }; if (arg) { total += arg; } return inner; }; console.log('Currying : ', sum(1)(2)(3)()) // 6
β
Build custom .map
Array.prototype.mapV2 = function(fn) { const results = []; for (let i = 0; i < this.length; i++) { const response = fn(this[i]); results.push(response); } return results; }; const addOne = n => n + 1; const r = [1, 2, 3].mapV2(addOne); console.log(r);
β
Create _.get from lodash
const obj = { A: { B: { c: 10 } } } const get = (obj, path) => { const pathArr = path.split('.'); // ['A', 'B', 'c'] const getValue = (obj, pathArr) => { const [firstPath, ...rest] = pathArr; const value = obj[firstPath]; if (typeof value === 'object') { return getValue(value, rest); } else { return value; } }; return getValue(obj, pathArr); }; console.log(get(obj, 'A.B.c')); console.log(get(obj, 'A.B.d'));
β
Format characters: Split string into β€9 char blocks
Given an input string, print the total number of characters.
If characters are more than 9 then split it into multiple block.
ex., if there are 10 consecutive 'A's then it should print '9A1A' instead of '10A'
const format = (str) => { let tempChar, count; const result = []; for (let i = 0; i < str.length; i++) { const char = str[i]; if (!tempChar) { tempChar = char; count = 0; } if (tempChar === char && count < 9) { count++; } else { result.push(`${count}${tempChar}`) tempChar = char; count = 1; } } result.push(`${count}${tempChar}`) return result.join(''); }; console.log(format('AAAABBCCCCC')) // 4A2B5C console.log(format('AAAAAAAAAA')) // 9A1A
β
Rearrange array: Move target elements to end
Given an array and a target element, move all the target element to the end of the array.
const organize = (arr, target) => { let totalTargets = 0; const result = arr.filter(item => { if (item === target) { totalTargets++; } return item !== target; }); return [...result, ...Array(totalTargets).fill(target)]; }; console.log(organize([2, 1, 2, 3, 4, 1, 2], 2)) // [1,3,4,1,2,2,2]
π Questions + Solutions here:
π Replit β Upstox R1
π§ Master these to crack your next JS interview.
Top comments (0)