Created
January 7, 2019 17:44
-
-
Save zer0id0/4dfe311a8f85b69a5291813244969330 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Write a function that prints the temperature closest to 0 among input data. | |
* If two numbers are equally close to zero, positive integer has to be considered closest to zero (for instance, if the temperatures are -5 and 5, then display 5) | |
*/ | |
const temps = [ | |
'1 -1 -3 3 2', | |
'-4 -2 -111', | |
'12 -1 3 6 2 9', | |
'12 2 6 9 -2 7', | |
'-5 -4 -2 7 -20 4 2 18 11 5', | |
'' | |
]; | |
// --- | |
// Receive string of temps one after each other | |
function outputTemp(tempRow) { | |
if (tempRow.length === 0) return 0 | |
const tempArr = tempRow.split(' ').map(x => parseInt(x)); | |
// console.log(tempArr); | |
if (tempArr.indexOf(0) !== -1) return 0; | |
const minPosTemp = Math.min(...tempArr.filter(x => x > 0)); | |
const minNegTemp = Math.max(...tempArr.filter(x => x < 0)); | |
return Math.abs(minPosTemp) <= Math.abs(minNegTemp) ? minPosTemp : minNegTemp; | |
if (Math.abs(minPosTemp) <= Math.abs(minPosTemp)) { | |
minPosTemp | |
}else { | |
minNegTemp; | |
} | |
} | |
console.log(outputTemp('1 -1 -3 3 2')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment