Skip to content

Instantly share code, notes, and snippets.

@rofrol
Last active March 27, 2018 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rofrol/bc56dc4bb9b3e3372ff4c9acee7cbabd to your computer and use it in GitHub Desktop.
Save rofrol/bc56dc4bb9b3e3372ff4c9acee7cbabd to your computer and use it in GitHub Desktop.
flatten.js
/*
Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
Your solution should be a link to a gist on gist.github.com with your implementation.
When writing this code, you can use any language you're comfortable with. The code must be well tested and documented if necessary, and in general please treat the quality of the code as if it was ready to ship to production.
Try to avoid using language defined methods like Ruby's Array#flatten.*
*/
const flatten = a => a.reduce((acc, item) => {
if(Array.isArray(item)) {
acc.push(...flatten(item));
} else {
acc.push(item);
}
return acc;
}, []);
function arraysEqual(a1, a2) {
if(!Array.isArray(a1) || !Array.isArray(a2) || a1.length !== a2.length) return false;
for(let i = 0; i < a1.length; ++i) {
if(a1[i] != a2[i]) return false;
}
return true;
}
function assert(condition, message) {
if (!condition) {
message = message || "Assertion failed";
if (typeof Error !== "undefined") {
throw new Error(message);
}
throw message; // Fallback
}
}
function test() {
var toFlatten = [[1,2,[3]],4];
var expected = [1,2,3,4];
var wrong = [1,2,3,4,5];
var result = flatten(toFlatten);
assert(arraysEqual(expected, result))
assert(arraysEqual(wrong, result))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment