Skip to content

Commit 6629463

Browse files
solved iteration ironhack-labs#3 and ironhack-labs#3.1 (except error)
1 parent bb69688 commit 6629463

File tree

1 file changed

+16
-17
lines changed

1 file changed

+16
-17
lines changed

src/functions-and-arrays.js

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ function maxOfTwoNumbers(num1, num2) {
1212
}
1313
}
1414

15+
1516
// ----------------------------------------
1617
// Iteration #2: Find longest word
1718
// ----------------------------------------
@@ -54,32 +55,29 @@ function findLongestWord(array) {
5455
const numbers = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10];
5556

5657
function sumNumbers(array) {
57-
let result = "";
58+
let result = 0;
59+
let zeroCounter = 0;
5860

5961
// return zero if receives an empty array when called
6062
if (array.length == 0) {
6163
return 0;
6264
}
65+
// return the sum with one number array
6366
else if (array.length == 1) {
6467
return array[0];
6568
}
69+
// return zero if all elements are zero
70+
// return the sum when passed array of numbers
6671
else {
6772
for (let i = 0; i < array.length; i++) {
68-
let zeroCounter = 0;
69-
70-
if (array[i] === 0) {
73+
if (array[i] == 0) {
7174
zeroCounter++;
7275
}
7376
else {
7477
result += array[i];
7578
}
7679
}
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) {
8381
return 0;
8482
}
8583
else {
@@ -88,10 +86,6 @@ function sumNumbers(array) {
8886
}
8987
}
9088

91-
sumNumbers(numbers);
92-
93-
94-
9589

9690
// ----------------------------------------
9791
// Iteration #3.1 Bonus:
@@ -100,27 +94,32 @@ sumNumbers(numbers);
10094
function sum(array) {
10195
let result = 0;
10296

97+
// return zero if receives an empty array when called
10398
if (array.length == 0) {
10499
return 0;
105100
}
101+
// return sum when passed one number array
106102
else if (array.length == 1) {
107103
return array[0];
108104
}
105+
// return sum when passed array of strings, numbers or booleans
106+
// return sum when passed array of mixed datatypes
109107
else {
110108
for (let i = 0; i < array.length; i++) {
111-
//result += array[i];
112109
if (typeof array[i] === "number") {
113-
result += array[i];
110+
result += array[i];
114111
}
115112
else if(typeof array[i] === "string") {
116113
result +=array[i].length;
117114
}
118115
else if (typeof array[i] === "boolean" && array[i] === true) {
119116
result++;
120117
}
118+
// throw error when unsupported data type (object or array) present in array
121119
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! :-(");
123121
}
122+
else{}
124123
}
125124
return result;
126125
}

0 commit comments

Comments
 (0)