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