|
1 | 1 | /**
|
2 | 2 | * @function alphaNumericPalindrome
|
3 |
| - * @description alphaNumericPalindrome should return true if the string has alphanumeric characters that are palindrome irrespective of special characters and the letter case. |
| 3 | + * @description alphaNumericPalindrome should return true if the string has alphanumeric characters that form a palindrome, |
| 4 | + * regardless of special characters and letter case. |
4 | 5 | * @param {string} str the string to check
|
5 | 6 | * @returns {boolean}
|
6 | 7 | * @see [Palindrome](https://en.wikipedia.org/wiki/Palindrome)
|
7 | 8 | * @example
|
8 | 9 | * The function alphaNumericPalindrome() receives a string with varying formats
|
9 |
| - * like "racecar", "RaceCar", and "race CAR" |
| 10 | + * like "racecar", "RaceCar", and "race CAR". |
10 | 11 | * The string can also have special characters
|
11 |
| - * like "2A3*3a2", "2A3 3a2", and "2_A3*3#A2" |
| 12 | + * like "2A3*3a2", "2A3 3a2", and "2_A3*3#A2". |
12 | 13 | *
|
13 | 14 | * But the catch is, we have to check only if the alphanumeric characters
|
14 |
| - * are palindrome i.e remove spaces, symbols, punctuations etc |
15 |
| - * and the case of the characters doesn't matter |
| 15 | + * form a palindrome, i.e., remove spaces, symbols, punctuation, etc. |
| 16 | + * The case of the characters doesn't matter. |
16 | 17 | */
|
17 | 18 | const alphaNumericPalindrome = (str) => {
|
18 | 19 | if (typeof str !== 'string') {
|
19 | 20 | throw new TypeError('Argument should be string')
|
20 | 21 | }
|
21 | 22 |
|
22 |
| - // removing all the special characters and turning everything to lowercase |
| 23 | + // Remove all non-alphanumeric characters and convert to lowercase |
23 | 24 | const newStr = str.replace(/[^a-z0-9]+/gi, '').toLowerCase()
|
| 25 | + |
24 | 26 | const midIndex = newStr.length >> 1 // x >> y = floor(x / 2^y)
|
25 | 27 |
|
26 | 28 | for (let i = 0; i < midIndex; i++) {
|
27 | 29 | if (newStr.at(i) !== newStr.at(~i)) {
|
28 |
| - // ~n = -(n + 1) |
| 30 | + // ~n = -(n + 1), used to get characters from the end |
29 | 31 | return false
|
30 | 32 | }
|
31 | 33 | }
|
|
0 commit comments