| 7 | 8 | * @param {string} number |
| 8 | 9 | * @returns {boolean} |
| 9 | 10 | */ |
| 10 | | export const valid = (number) => { |
| 11 | | throw new Error('Remove this line and implement the function'); |
| 11 | const valid = (number) => { |
| 12 | // Edge Case: Strings of length 1 or less are not valid |
| 13 | if (number.length <= 1) { |
| 14 | return false; |
| 15 | } |
| 16 | |
| 17 | // Remove all spaces from the string |
| 18 | const cleanedNumber = number.replace(/\s/g, ''); |
| 19 | |
| 20 | // Edge Case: Strings with only spaces (after cleaning become empty) |
| 21 | if (cleanedNumber.length === 0) { |
| 22 | return false; |
| 23 | } |
| 24 | |
| 25 | // Edge Case: Strings with non-digit characters are disallowed |
| 26 | if (!/^\d+$/.test(cleanedNumber)) { |
| 27 | return false; |
| 28 | } |
| 29 | |
| 30 | let sum = 0; |
| 31 | const length = cleanedNumber.length; |
| 32 | |
| 33 | // Process digits from right to left |
| 34 | for (let i = length - 1; i >= 0; i--) { |
| 35 | let digit = parseInt(cleanedNumber[i], 10); |
| 36 | |
| 37 | // Double every second digit starting from the right |
| 38 | if ((length - 1 - i) % 2 === 1) { |
| 39 | digit *= 2; |
| 40 | // If doubling results in a number > 9, subtract 9 |
| 41 | if (digit > 9) { |
| 42 | digit -= 9; |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | sum += digit; |
| 47 | } |
| 48 | |
| 49 | // The number is valid if the sum is divisible by 10 |
| 50 | return sum % 10 === 0; |
| 12 | 51 | }; |
| 52 | |
| 53 | // Handled Edge Cases: Strings of length 1 or less, strings with only spaces, strings with non-digit characters |
| 54 | |
| 55 | module.exports = { valid }; |
| 56 | } |