1+ const numberInput = document . getElementById ( 'numberInput' ) ; //number input
2+ const result = document . getElementById ( 'result' ) ; //result display
3+ const option = document . getElementById ( 'option' ) ; //option selection
4+ let mode = option . value ;
5+ function calculateSumOfDigits ( ) { //calculate sum of digits
6+ const number = parseFloat ( numberInput . value ) ; //get number value from input
7+ if ( isNaN ( number ) ) { //if entered number is not a number
8+ result . textContent = 'Please enter a valid number.' ;
9+ }
10+ const sum = calculateSum ( number ) ; //calculate sum of entered number
11+ result . textContent = sum ; //display result
12+ }
13+ function calculateSumOfAllDigits ( number ) { //calculate sum of all digits
14+ const numberString = number . toString ( ) . split ( 'e' ) [ 0 ] . replaceAll ( '.' , '' ) . replaceAll ( '-' , '' ) ; //remove non digit characters to avoid errors
15+ let sum = 0 ;
16+ for ( let i = 0 ; i < numberString . length ; i ++ ) {
17+ const digit = parseInt ( numberString [ i ] , 10 ) ;
18+ sum += digit * digit ; //square each digit
19+ }
20+ return sum ;
21+ }
22+
23+ function calculateSumOfIntegerDigits ( number ) { //calculate sum of integer digits
24+ const integerString = parseInt ( number , 10 ) . toString ( ) . replaceAll ( '.' , '' ) . replaceAll ( '-' , '' ) ; //remove non digit characters to avoid errors
25+ let sum = 0 ;
26+ for ( let i = 0 ; i < integerString . length ; i ++ ) {
27+ const digit = parseInt ( integerString [ i ] , 10 ) ;
28+ sum += digit * digit ; //square each digit
29+ }
30+ return sum ;
31+ }
32+
33+ function calculateSum ( number ) { //calculate sum function
34+ if ( mode === 'sumOfDigits' ) { //if mode is sum of digits
35+ return calculateSumOfAllDigits ( number ) ; //return sum of all digits
36+ } else if ( mode === 'sumOfIntegerDigits' ) { //else if mode is sum of integer digits
37+ return calculateSumOfIntegerDigits ( number ) ; //return sum of integer digits
38+ }
39+ }
0 commit comments