|
8 | 8 | // 4. Below the function, define and initialize a variable to hold a string.
|
9 | 9 | // 5. Use console.log(reverseCharacters(myVariableName)); to call the function and verify that it correctly reverses the characters in the string.
|
10 | 10 | // 6. Optional: Use method chaining to reduce the lines of code within the function.
|
11 |
| - |
12 | 11 | // Part Two: Reverse Digits
|
13 |
| - |
14 | 12 | // 1. Add an if statement to reverseCharacters to check the typeof the parameter.
|
15 | 13 | // 2. If typeof is ‘string’, return the reversed string as before.
|
16 | 14 | // 3. If typeof is ’number’, convert the parameter to a string, reverse the characters, then convert it back into a number.
|
17 |
| -// 4. Return the reversed number. |
| 15 | +// 4. Return the reversed number |
18 | 16 | // 5. Be sure to print the result returned by the function to verify that your code works for both strings and numbers. Do this before moving on to the next exercise.
|
19 |
| - |
20 | 17 | // Part Three: Complete Reversal
|
21 | 18 |
|
| 19 | + |
| 20 | +function reverseCharacters(original){ |
| 21 | + let reverse = ''; |
| 22 | + if(typeof original === String){ |
| 23 | + reverse = original.split('').reverse().join(''); |
| 24 | + } |
| 25 | + else if(typeof original !== String){ |
| 26 | + reverse = original.toString().split('').reverse().join(''); |
| 27 | + |
| 28 | + } else{ |
| 29 | + console.log("nothing else"); |
| 30 | + } |
| 31 | + |
| 32 | + return reverse; |
| 33 | +} |
| 34 | +console.log(reverseCharacters("apples")); |
| 35 | + |
22 | 36 | // 1. Define and initialize an empty array.
|
23 | 37 | // 2. Loop through the old array.
|
| 38 | + |
| 39 | +let arrayTest1 = ['apple', 'potato', 'Capitalized Words']; |
| 40 | +let arrayTest2 = [123, 8897, 42, 1168, 8675309]; |
| 41 | +let arrayTest3 = ['hello', 'world', 123, 'orange']; |
| 42 | + |
| 43 | +function doubleReverse(originalArray){ |
| 44 | + let oldArray = []; |
| 45 | + |
| 46 | + for(i = 0; i < originalArray.length; i++){ |
| 47 | + oldArray.push(reverseCharacters(originalArray[i])); |
| 48 | + |
| 49 | + } return oldArray.reverse(); |
| 50 | +} |
| 51 | +console.log(doubleReverse(arrayTest3)); |
| 52 | + |
| 53 | + |
24 | 54 | // 3. For each element in the old array, call reverseCharacters to flip the characters or digits.
|
25 | 55 | // 4. Add the reversed string (or number) to the array defined in part ‘a’.
|
26 | 56 | // 5. Return the final, reversed array.
|
27 | 57 | // 6. Be sure to print the results from each test case in order to verify your code.
|
28 | 58 |
|
29 |
| -let arrayTest1 = ['apple', 'potato', 'Capitalized Words']; |
30 |
| -let arrayTest2 = [123, 8897, 42, 1168, 8675309]; |
31 |
| -let arrayTest3 = ['hello', 'world', 123, 'orange']; |
| 59 | + |
32 | 60 |
|
33 | 61 | // Bonus Missions
|
34 | 62 |
|
|
0 commit comments