Review a JavaScript flatten PR
ElasticSoftware Engineer · Technical ScreenLast updated
This question evaluates a candidate's understanding of JavaScript recursion, array manipulation, API contract reasoning, and correctness when implementing a flatten utility.
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:
inputis 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
// 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
- Identify correctness bugs and edge cases this implementation fails.
- Discuss API/contract questions you would clarify (e.g., how to treat non-array objects,
null, sparse arrays, strings). - Suggest improvements for:
- readability and maintainability
- performance (time/space)
- safety (e.g., stack overflow risk)
- Propose a revised approach (pseudocode or description is fine) and a minimal set of tests you would request before approving.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.