Skip to content

Commit 773572b

Browse files
committed
while
1 parent 5b83486 commit 773572b

File tree

4 files changed

+36
-12
lines changed

4 files changed

+36
-12
lines changed

Exercises/1-for.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
11
'use strict';
22

33
const sum = (...args) => {
4-
// Use for loop and accumulator variable
5-
// to calculate sum of all given arguments
6-
// For example sum(1, 2, 3) should return 6
4+
let answer = 0;
5+
const len = args.length;
6+
7+
for (let i = 0; i < len; ++i) {
8+
answer += args[i];
9+
}
10+
11+
return answer;
712
};
813

914
module.exports = { sum };

Exercises/2-for-of.js

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
'use strict';
22

33
const sum = (...args) => {
4-
// Use for..of loop and accumulator variable
5-
// to calculate sum of all given arguments
6-
// For example sum(1, 2, 3) should return 6
4+
let answer = 0;
5+
6+
for (const num of args) {
7+
answer += num;
8+
}
9+
10+
return answer;
711
};
812

913
module.exports = { sum };

Exercises/3-while.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
'use strict';
22

33
const sum = (...args) => {
4-
// Use while loop and accumulator variable
5-
// to calculate sum of all given arguments
6-
// For example sum(1, 2, 3) should return 6
4+
let answer = 0;
5+
let num = args.pop();
6+
7+
while (num) {
8+
answer += num;
9+
num = args.pop();
10+
}
11+
12+
return answer;
713
};
814

915
module.exports = { sum };

Exercises/4-do-while.js

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,18 @@
11
'use strict';
22

33
const sum = (...args) => {
4-
// Use do..while loop and accumulator variable
5-
// to calculate sum of all given arguments
6-
// For example sum(1, 2, 3) should return 6
4+
let answer = 0;
5+
6+
do {
7+
let num = args.pop();
8+
} while (args.length > 0) {
9+
answer += num;
10+
num = args.pop();
11+
}
12+
13+
return answer;
714
};
815

16+
console.log(sum());
17+
918
module.exports = { sum };

0 commit comments

Comments
 (0)