-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhighlow
38 lines (34 loc) · 1.57 KB
/
highlow
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
this one was a bit tricky. I had to make use of typeof a few times to realize that they were being passed as a string. I read the
instructions incorrectly. they were "valid" int32s inside a string. I missed the "string" part and assumed it was an array of int32s.
I am curious to see what the solutions show and what I can learn this time.
the first solution ... math.max. I guess it goes to show that if you look into the math methods you may find what you are looking for.
curiously though I learned something else from this. the "map" method from arrays may be able to build the integers array along with the split.
this could have prevented all the calls for parseInt.
function highAndLow(numbers){
numbers = numbers.split(' ').map(Number);
return Math.max.apply(0, numbers) + ' ' + Math.min.apply(0, numbers);
}
*/
function highAndLow(numbers){
//split the string into an array by the spaces.
var numArray = numbers.split(' ');
//declare and fill the highest to prevent undefined which will screw up the comparisons.
var highest = parseInt(numArray[0]);
//declare and fill the lowest to prevent undefined which will screw up the comparisons.
var lowest = parseInt(numArray[0]);
//loop thorugh the array
for (n of numArray){
//compare n to highest
if( parseInt(n) > highest){
//fill highest with N parsing it asn an int as well because we started with a string.
highest = parseInt(n);
//compare n to lowest.
}else if(parseInt(n) < lowest){
//fill lowest with N
lowest = parseInt(n);
}
}
//return highest and lowest with a space between.
return highest + ' ' + lowest;
}