|
1 | 1 | function cardValidator(num) { |
2 | | - const numStr = num.toString(); // Convert to string for iteration with this we can check the length and individual checks |
3 | | - if (numStr.length !== 16 || !/^[0-9]+$/.test(numStr) || numStr[numStr.length -1] % 2 === 1) { |
4 | | - console.log("I stopped because one of my condition is true") |
5 | | - return false; // Check length is 16 numbers long, if it only contains digits and if the last digits is even |
| 2 | + const numStr = num.toString(); // Convert to string for iteration and validation |
| 3 | + |
| 4 | + // Initial validation conditions: |
| 5 | + if ( |
| 6 | + numStr.length !== 16 || // Must be exactly 16 digits long |
| 7 | + !/^[0-9]+$/.test(numStr) || // Must contain only numbers |
| 8 | + numStr[numStr.length - 1] % 2 === 1 || // Last digit must be even |
| 9 | + numStr.split("").map(Number).reduce((acc, val) => acc + val, 0) <= 16 // Sum of digits must be greater than 16 |
| 10 | + ) { |
| 11 | + console.log("I stopped because one of my conditions is true"); |
| 12 | + return false; |
6 | 13 | } |
7 | 14 |
|
8 | | - let firstDigit = numStr[0]; // Track the first digit to compare with the rest digits |
| 15 | + // Check if all digits are the same: |
| 16 | + const firstDigit = numStr[0]; |
9 | 17 | for (let i = 1; i < numStr.length; i++) { |
10 | | - // console.log(`compare ${numStr[i]} con ${firstDigit} in position ${i}`); |
11 | | - |
12 | 18 | if (numStr[i] !== firstDigit) { |
13 | | - // console.log(`different digit found: ${numStr[i]}`); |
14 | 19 | return true; // Found at least two different digits |
15 | 20 | } |
16 | 21 | } |
17 | | - // console.log("all digits are distint to same."); |
| 22 | + |
18 | 23 | console.log(`The last digit (${numStr[numStr.length - 1]}) is odd, so the validation fails.`); |
19 | 24 | return false; // All digits are the same |
20 | 25 | } |
21 | 26 |
|
22 | | -console.log(cardValidator(1111111111111111)); // Output: false and stop in the first return. |
23 | | -console.log(cardValidator(1234567890123456)); // Output: true |
24 | | -console.log(cardValidator(2222222222222222)); // Output: false |
25 | | -console.log(cardValidator(3333333333333334)); // Output: true |
26 | | - |
| 27 | +// Test cases: |
| 28 | +console.log(cardValidator(1111111111111111)); // Output: false (all digits are the same) |
| 29 | +console.log(cardValidator(1234567890123456)); // Output: true (valid card) |
| 30 | +console.log(cardValidator(2222222222222222)); // Output: false (all digits are the same) |
| 31 | +console.log(cardValidator(3333333333333334)); // Output: true (valid card) |
0 commit comments