Skip to content

Commit f3ffada

Browse files
committed
Added easy/number_addition
1 parent 0963da8 commit f3ffada

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

easy/number_addition.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Have the function numberAddition(str) take the str parameter, search for all
3+
* the numbers in the string, add them together, then return that final number.
4+
* For example: if str is "88Hello 3World!" the output should be 91. You will
5+
* have to differentiate between single digit numbers and multiple digit numbers
6+
* like in the example above. So "55Hello" and "5Hello 5" should return two
7+
* different answers. Each string will contain at least one letter or symbol.
8+
*
9+
* https://www.coderbyte.com/results/bhanson:Number%20Addition:JavaScript
10+
*
11+
* @param {string} str
12+
* @return {number}
13+
*/
14+
function numberAddition(str) {
15+
const DIGITS = '0123456789';
16+
17+
let numbers = [];
18+
19+
// First find numbers
20+
for (let i = 0, number = ''; i < str.length; i++) {
21+
if (!DIGITS.includes(str[i])) {
22+
if (number !== '') {
23+
numbers.push(number);
24+
}
25+
number = '';
26+
} else {
27+
number += str[i];
28+
29+
// Special case for last char
30+
if (i === str.length - 1) {
31+
numbers.push(number);
32+
}
33+
}
34+
}
35+
36+
let sum = 0;
37+
for (let i = 0; i < numbers.length; i++) {
38+
sum += parseInt(numbers[i]);
39+
}
40+
return sum;
41+
}
42+
43+
module.exports = numberAddition;

easy/number_addition.test.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
const numberAddition = require('./number_addition');
2+
3+
describe('numberAddition()', () => {
4+
test('adds separated single digits in string', () => {
5+
expect(numberAddition('5fad4fadfa6')).toBe(15);
6+
});
7+
8+
test('treats consecutive digits as one number', () => {
9+
expect(numberAddition('28ad 11 fd as22dfa19')).toBe(80);
10+
});
11+
});

0 commit comments

Comments
 (0)