Review a JavaScript flatten PR
Company: Elastic
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Technical Screen
## Live PR Review: JavaScript `flatten` using recursion
You are reviewing a pull request that introduces a `flatten` utility.
### Intended behavior
Implement `flatten(input)` such that:
- `input` is an Array that may contain nested Arrays to arbitrary depth.
- The function returns a **new** flat Array preserving left-to-right order.
Examples:
- `flatten([1, [2, 3], [[4]], 5]) -> [1, 2, 3, 4, 5]`
- `flatten([]) -> []`
- `flatten([1, [2, [3]]]) -> [1, 2, 3]`
### PR code under review
```js
// PR version
export function flatten(arr) {
const out = [];
function helper(x) {
for (const i in x) {
const v = x[i];
if (typeof v === 'object') {
helper(v);
} else {
out.push(v);
}
}
}
helper(arr);
return out;
}
```
### Tasks
1. Identify **correctness bugs** and **edge cases** this implementation fails.
2. Discuss **API/contract** questions you would clarify (e.g., how to treat non-array objects, `null`, sparse arrays, strings).
3. Suggest improvements for:
- readability and maintainability
- performance (time/space)
- safety (e.g., stack overflow risk)
4. Propose a revised approach (pseudocode or description is fine) and a minimal set of tests you would request before approving.
Quick Answer: This question evaluates a candidate's understanding of JavaScript recursion, array manipulation, API contract reasoning, and correctness when implementing a flatten utility.