Skip to content

Instantly share code, notes, and snippets.

@jimmont
Last active February 22, 2020 18: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 jimmont/95d849d46a843d55223e6690712349e7 to your computer and use it in GitHub Desktop.
Save jimmont/95d849d46a843d55223e6690712349e7 to your computer and use it in GitHub Desktop.
array flat arbitrary
/*
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. Please include unit tests and any documentation you feel is necessary. In general, 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 or JavaScript's Array.flat.
*/
var list = [1,2, [3, 4, [5, 6]]];
/* @function flat
@summary flatten arbitrarily nested arrays without using the native feature
@description this isn't reality, it's an abitrary communication exercise
@example
// flatten an array
var list = [1,2, [3, 4, [5, 6]]];
flat(list);
// returns a new array [1,2,3,4,5,6] like `array.flat(Infinity)` method
@see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
*/
function flat(list, val, i, arr){
if(arr){
if(Array.isArray(val)){
val.reduce(flat, list);
}else{
list.push(val);
};
return list;
};
return list.reduce(flat, []);
}
var result = flat(list);
console.log(`assertions: ${ [
console.assert(result.join() === list.flat(Infinity).join(), 'native and manual results match')
,console.assert(result.join('') === '123456', 'result is explicitly checked')
].length }
against method "flat"
input: ${ list.join(',') }
output: ${ result.join(',') }
`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment