@@ -12,6 +12,7 @@ function maxOfTwoNumbers(num1, num2) {
12
12
}
13
13
}
14
14
15
+
15
16
// ----------------------------------------
16
17
// Iteration #2: Find longest word
17
18
// ----------------------------------------
@@ -54,32 +55,29 @@ function findLongestWord(array) {
54
55
const numbers = [ 6 , 12 , 1 , 18 , 13 , 16 , 2 , 1 , 8 , 10 ] ;
55
56
56
57
function sumNumbers ( array ) {
57
- let result = "" ;
58
+ let result = 0 ;
59
+ let zeroCounter = 0 ;
58
60
59
61
// return zero if receives an empty array when called
60
62
if ( array . length == 0 ) {
61
63
return 0 ;
62
64
}
65
+ // return the sum with one number array
63
66
else if ( array . length == 1 ) {
64
67
return array [ 0 ] ;
65
68
}
69
+ // return zero if all elements are zero
70
+ // return the sum when passed array of numbers
66
71
else {
67
72
for ( let i = 0 ; i < array . length ; i ++ ) {
68
- let zeroCounter = 0 ;
69
-
70
- if ( array [ i ] === 0 ) {
73
+ if ( array [ i ] == 0 ) {
71
74
zeroCounter ++ ;
72
75
}
73
76
else {
74
77
result += array [ i ] ;
75
78
}
76
79
}
77
-
78
- if ( result === 0 && zeroCounter === array . length ) {
79
- return 0 ;
80
- }
81
-
82
- if ( result === 0 && array . forEach ( ( num ) => num === 0 ) ) {
80
+ if ( zeroCounter == array . length ) {
83
81
return 0 ;
84
82
}
85
83
else {
@@ -88,10 +86,6 @@ function sumNumbers(array) {
88
86
}
89
87
}
90
88
91
- sumNumbers ( numbers ) ;
92
-
93
-
94
-
95
89
96
90
// ----------------------------------------
97
91
// Iteration #3.1 Bonus:
@@ -100,27 +94,32 @@ sumNumbers(numbers);
100
94
function sum ( array ) {
101
95
let result = 0 ;
102
96
97
+ // return zero if receives an empty array when called
103
98
if ( array . length == 0 ) {
104
99
return 0 ;
105
100
}
101
+ // return sum when passed one number array
106
102
else if ( array . length == 1 ) {
107
103
return array [ 0 ] ;
108
104
}
105
+ // return sum when passed array of strings, numbers or booleans
106
+ // return sum when passed array of mixed datatypes
109
107
else {
110
108
for ( let i = 0 ; i < array . length ; i ++ ) {
111
- //result += array[i];
112
109
if ( typeof array [ i ] === "number" ) {
113
- result += array [ i ] ;
110
+ result += array [ i ] ;
114
111
}
115
112
else if ( typeof array [ i ] === "string" ) {
116
113
result += array [ i ] . length ;
117
114
}
118
115
else if ( typeof array [ i ] === "boolean" && array [ i ] === true ) {
119
116
result ++ ;
120
117
}
118
+ // throw error when unsupported data type (object or array) present in array
121
119
else if ( typeof array [ i ] === "object" || typeof array [ i ] === "array" ) {
122
- throw new Error ( 'SORRY, unsupported datatype' ) ;
120
+ throw new Error ( "Errow: Unsupported data type (object or array) present in your array! :-(" ) ;
123
121
}
122
+ else { }
124
123
}
125
124
return result ;
126
125
}
0 commit comments