JS Machine Coding Questions — Implementations You Must Know
Deep clone
- Copy nested objects/arrays so nested values are new references.
- Key insight: If value is not an object (or is null), return it. Otherwise build a new array or plain object and recurse.
- Gotcha: Does not handle circular refs (infinite loop). For production, use structuredClone(obj) (built-in) or a WeakMap to detect cycles.
- Gotcha: Date / Map / Set need special cases if you go beyond plain objects.
1function deepClone(obj) {
2 if (obj === null || typeof obj !== "object") return obj;
3
4 const copy = Array.isArray(obj) ? [] : {};
5
6 for (let key in obj) {
7 copy[key] = deepClone(obj[key]);
8 }
9
10 return copy;
11}