| 3 | 3 | // convenience to get you started writing code faster. |
| 4 | 4 | // |
| 5 | 5 | |
| 6 | | export const encode = () => { |
| 7 | | throw new Error('Remove this line and implement the function'); |
| 6 | export const encode = (input) => { |
| 7 | if (!input) return ''; // Edge Case: empty string |
| 8 | |
| 9 | let result = ''; |
| 10 | let count = 1; |
| 11 | let currentChar = input[0]; |
| 12 | |
| 13 | for (let i = 1; i <= input.length; i++) { |
| 14 | // Edge Case: end of string |
| 15 | if (i === input.length) { |
| 16 | result += (count > 1 ? count : '') + currentChar; |
| 17 | break; |
| 18 | } |
| 19 | |
| 20 | // Edge Case: character change |
| 21 | if (input[i] !== currentChar) { |
| 22 | result += (count > 1 ? count : '') + currentChar; |
| 23 | currentChar = input[i]; |
| 24 | count = 1; |
| 25 | } else { |
| 26 | count++; |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | return result; |
| 31 | // Handled Edge Cases: empty string, end of string, character change |
| 8 | 32 | }; |
| 9 | 33 | |
| 10 | | export const decode = () => { |
| 11 | | throw new Error('Remove this line and implement the function'); |
| 34 | export const decode = (input) => { |
| 35 | if (!input) return ''; // Edge Case: empty string |
| 36 | |
| 37 | let result = ''; |
| 38 | let i = 0; |
| 39 | |
| 40 | while (i < input.length) { |
| 41 | let count = ''; |
| 42 | |
| 43 | // Edge Case: parsing multi-digit numbers |
| 44 | while (i < input.length && /\d/.test(input[i])) { |
| 45 | count += input[i]; |
| 46 | i++; |
| 47 | } |
| 48 | |
| 49 | // Edge Case: single character with no preceding number |
| 50 | const repeatCount = count ? parseInt(count, 10) : 1; |
| 51 | |
| 52 | // Edge Case: end of string or invalid input |
| 53 | if (i >= input.length) { |
| 54 | break; |
| 55 | } |
| 56 | |
| 57 | const char = input[i]; |
| 58 | result += char.repeat(repeatCount); |
| 59 | i++; |
| 60 | } |
| 61 | |
| 62 | return result; |
| 63 | // Handled Edge Cases: empty string, parsing multi-digit numbers, single character with no preceding number, end of string or invalid input |
| 12 | 64 | }; |