I have got this interview question which has asked me to write a production level code which flattens the arbitrary nested array of arrays.
Code
/**
* Flattens the array of arrays.
*
* @param {!Array<?>} elements The nested array elements.
* @return {!Array<?>} The flat list of array objects.
*/
function flatten(elements) {
return elements.reduce(function(result, current) {
if (Array.isArray(current)) {
return result.concat(flatten(current));
}
return result.concat(current);
}, []);
};
/**
* Compares two arrays.
*
* @param {!Array<T>} a
* @param {!Array<T>} b
* @template T
* @return {boolean} Whether two arrays are equal.
*/
function assertArrayEqual(a, b) {
// Guard clause
if (a.length != b.length) {
return false;
}
for (var i = a.length; i >= 0; i--) {
if (a[i] !== b[i]) {
return false
}
}
return true;
};
Test Suite
I think it would be good to show some TDD skills but I have avoided to use some external library instead don't know if its a good idea from interviewers' point of view.
console.log(assertArrayEqual(flatten([]), flatten([])));
console.log(assertArrayEqual(flatten([1]), flatten([1])));
console.log(assertArrayEqual(flatten([1, 2]), flatten([1, 2])));
console.log(assertArrayEqual(flatten([1, 2, 3]), flatten([1, 2, 3])));
console.log(assertArrayEqual(flatten([1, 2, [3]]), flatten([1, 2, 3])));
console.log(assertArrayEqual(flatten([1, 2, [3], [4, [5]]]), flatten([1, 2, 3, 4, 5])));
console.log(assertArrayEqual(flatten([[1, 2, [3]], 4]), flatten([1, 2, 3, 4])));
Questions
I haven't really handled an error condition here, should I check if the passed input is an array type or not?
Seeing the simplicity of the question I have avoided the added complexity of the OOP and followed a functional approach instead.
I think I have covered the documentation well but any suggestions are welcomes(I think it can be modified if I decide to throw an exception).
It seemed overkill to use module pattern or some other fancy stuff.
I am using closure compiler to catch bugs earlier during development.
Any other suggestions are welcomed here :)
Array.isArray
andarray.reduce
are both supported. \$\endgroup\$var a = []; a.push(a); flatten(a);
, or at least to document that they're not supported? \$\endgroup\$