Skip to content

Commit 41ac617

Browse files
committed
refa: prefer locallity over separation
1 parent 3f87cbb commit 41ac617

File tree

1 file changed

+13
-26
lines changed

1 file changed

+13
-26
lines changed

src/interview-classics/is-palindrome/is-palindrome-method.js

+13-26
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,25 @@
1-
const tokensToRemove = /[.,:;?!\s]/g
1+
// Characters to remove from string in order to normalize it
2+
const charsToRemove = /[.,:;?!\s]/g
23

34
/**
4-
* Remove tokens and convert to lowercase.
5+
* Checks if a string is a palindrome.
6+
*
7+
* Time complexity: O(n)
8+
* Space complexity: O(n)
59
*
6-
* @private
7-
* @param {string} str String to normalize
8-
* @returns {string} Normalized string.
10+
* @param {string} str String to be checked.
11+
* @returns {boolean} Whether the string is a palindrome.
912
*/
10-
const normalize = (str) =>
11-
str
12-
.replace(tokensToRemove, '')
13+
const isPalindrome = (str) => {
14+
const normalStr = str
15+
.replace(charsToRemove, '')
1316
.toLowerCase()
1417

15-
/**
16-
* Reverse the order of characters.
17-
*
18-
* @param {string} str String to reverse.
19-
* @returns {string} Reversed string.
20-
*/
21-
const reverse = (str) =>
22-
[...str]
18+
const reverseNormalStr = [...normalStr]
2319
.reverse()
2420
.join('')
2521

26-
/**
27-
* Checks if a string is a palindrome.
28-
* Complexity: time O(n) because normalize and reverse always happen,
29-
* space O(n).
30-
* @param {string} str String to be checked.
31-
* @returns {boolean} True if the string is a palindrome, false otherwise.
32-
*/
33-
const isPalindrome = (str) => {
34-
const normalStr = normalize(str)
35-
return normalStr === reverse(normalStr)
22+
return normalStr === reverseNormalStr
3623
}
3724

3825
module.exports = {

0 commit comments

Comments
 (0)