Skip to content

Instantly share code, notes, and snippets.

@surprisetalk
Created March 6, 2018 01:55
Show Gist options
  • Save surprisetalk/eb4cdacd215cfc38a507850c6c52dee0 to your computer and use it in GitHub Desktop.
Save surprisetalk/eb4cdacd215cfc38a507850c6c52dee0 to your computer and use it in GitHub Desktop.
Flatten Integers
// FLATTEN INTEGERS /////////////////////////////////////////////////////////////////////
const flattenIntegers = ints =>
///// Transforms nested lists of integers into a flat list of integers.
///// e.g. 1 -> error
///// e.g. [ 1 ] -> [1 ]
///// e.g. [[1,2,[3]],4] -> [1,2,3,4]
{
const concatLists = lists =>
///// Transforms a list of lists into a single list.
///// e.g. [ 1 ] -> error
///// e.g. [[1,2],[3],[],[4]] -> [1,2,3,4]
[].concat.apply( [], lists );
const flattenInteger = int =>
///// Transforms a single integer or nested list of integers into a list of integers.
///// e.g. "1" -> error
///// e.g. 1.1 -> error
///// e.g. 1.0 -> [ 1 ]
///// e.g. 1 -> [ 1 ]
///// e.g. [ 1 ] -> [ 1 ]
///// e.g. [ 1, [ 2 ] ] -> [ 1, 2 ]
{
if( Number.isInteger( int ) )
return [ int ];
////// This is our recursion base-case!
////// We ALWAYS want to return a list of integers.
else if( Array.isArray( int ) )
return concatLists( int.map( flattenInteger ) );
////// We transform each member of the list into a list of integers, and then concatenate them all together.
else
throw `flattenIntegers expected an array whose members are integers or lists of integers, but it received ${ JSON.stringify( int ) }`;
};
if( Array.isArray( ints ) )
return concatLists( ints.map( flattenInteger ) );
////// We transform each member of the list into a list of integers, and then concatenate them all together.
else
throw `flattenIntegers expected an array, but it received ${ JSON.stringify( ints ) }`;
};
// VERIFICATION /////////////////////////////////////////////////////////////////////////
console.log( flattenIntegers( [[1,2,[3]],4] ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment