File tree 2 files changed +54
-0
lines changed
2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change
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 ;
Original file line number Diff line number Diff line change
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
+ } ) ;
You can’t perform that action at this time.
0 commit comments