I recently took a coding test for a promotion at work. This was one of the tasks I really struggled with and was wondering what is the best way to do this. I used a load of
I'd use JavaScript's Date object to determine if a particular time was valid, by parsing the string as an ISO datetime string (like 1970-01-01T62:87) and then testing !isNaN( aDateInstance.getTime() ) and comparing the Date instance with the earlier saved largest Date instance (if applicable):
// permutator() borrowed from https://stackoverflow.com/a/20871714
function permutator( inputArr ) {
var results = [];
function permute( arr, memo ) {
var cur, memo = memo || [];
for( var i = 0; i < arr.length; i++ ) {
cur = arr.splice( i, 1 );
if( arr.length === 0 ) {
results.push( memo.concat( cur ) );
}
permute( arr.slice(), memo.concat( cur ) );
arr.splice( i, 0, cur[ 0 ] );
}
return results;
}
return permute( inputArr );
}
function generate( A, B, C, D ) {
var r = null;
permutator( [ A, B, C, D ] ).forEach( function( p ) {
var d = new Date( '1970-01-01T' + p[ 0 ] + '' + p[ 1 ] + ':' + p[ 2 ] + '' + p[ 3 ] );
if( !isNaN( d.getTime() ) && d > r ) {
r = d;
}
} );
var h, m;
return r ? ( ( h = r.getHours() ) < 10 ? '0' + h : h ) + ':' + ( ( m = r.getMinutes() ) < 10 ? '0' + m : m ) : 'NOT POSSIBLE';
}