🧠 Phần 6: Phỏng vấn Tình Huống & Logic
Dưới đây là tổng hợp đáp án phần 6: Phỏng vấn Tình Huống & Logic, giải thích ngắn gọn theo chuẩn Senior JavaScript Developer:
🔁 1. Viết hàm đảo ngược chuỗi mà không dùng hàm có sẵn
function reverseString(str) {
let result = '';
for (let i = str.length - 1; i >= 0; i--) {
result += str[i];
}
return result;
}
// Test
console.log(reverseString("hello")); // "olleh"
🔄 2. Viết hàm kiểm tra chuỗi có phải palindrome hay không
function isPalindrome(str) {
const len = str.length;
for (let i = 0; i < len / 2; i++) {
if (str[i] !== str[len - 1 - i]) return false;
}
return true;
}
// Test
console.log(isPalindrome("madam")); // true
console.log(isPalindrome("hello")); // false
⏱️ 3. Viết debounce function đơn giản
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
// Example usage
const log = debounce(() => console.log("Debounced!"), 300);
log(); log(); log(); // Chỉ in ra 1 lần sau 300ms nếu không bị gọi tiếp
➕ 4. Tính tổng các số trong mảng (dùng reduce
)
reduce
)const sumArray = arr => arr.reduce((acc, cur) => acc + cur, 0);
// Test
console.log(sumArray([1, 2, 3, 4])); // 10
🔤 5. Sắp xếp mảng object theo name
tăng dần
name
tăng dầnconst people = [
{ name: "Charlie" },
{ name: "Alice" },
{ name: "Bob" }
];
people.sort((a, b) => a.name.localeCompare(b.name));
console.log(people);
// [{ name: "Alice" }, { name: "Bob" }, { name: "Charlie" }]
🧬 6. Viết hàm deep clone một object lồng nhau
function deepClone(obj) {
if (obj === null || typeof obj !== "object") return obj;
if (Array.isArray(obj)) {
return obj.map(item => deepClone(item));
}
const result = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = deepClone(obj[key]);
}
}
return result;
}
// Test
const original = { a: 1, b: { c: 2, d: [3, 4] } };
const copy = deepClone(original);
copy.b.d[0] = 99;
console.log(original.b.d[0]); // 3 — không bị ảnh hưởng
🧩 7. Giải thích Promise.all()
hoạt động như thế nào
Promise.all()
hoạt động như thế nàoPromise.all()
nhận một mảng các Promise và trả về một Promise mới:
✅ Resolve nếu tất cả Promise đều resolve thành công → trả về mảng kết quả đúng thứ tự.
❌ Reject nếu bất kỳ Promise nào bị reject → dừng toàn bộ và trả về lỗi đầu tiên.
Ví dụ:
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
const p3 = Promise.resolve(3);
Promise.all([p1, p2, p3]).then(result => {
console.log(result); // [1, 2, 3]
});
const pErr = Promise.reject("Something failed!");
Promise.all([p1, pErr, p3]).catch(error => {
console.log(error); // "Something failed!"
});
Lưu ý kỹ thuật:
Dùng khi các tác vụ không phụ thuộc nhau nhưng cần tất cả cùng hoàn thành (VD: tải dữ liệu đồng loạt).
Không thích hợp nếu bạn muốn thực hiện từng phần một ngay cả khi 1 phần lỗi (
Promise.allSettled()
phù hợp hơn khi đó).
Last updated