Last active
November 10, 2020 20:09
-
-
Save anushshukla/059d0d54b1a7f4de8b314d6e8263c501 to your computer and use it in GitHub Desktop.
Palindrome Check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| String.prototype.isPalindrome = function(charIndex = 0) { | |
| const stringLength = this.length; | |
| const charIndexFromBehind = stringLength - charIndex - 1; | |
| const isCharSame = this[charIndex] === this[charIndexFromBehind]; | |
| if (!isCharSame) { | |
| return false; | |
| } | |
| const isIndexSame = charIndex === charIndexFromBehind; | |
| if (isIndexSame) { | |
| return true; | |
| } | |
| const nextCharIndex = charIndex + 1 | |
| return this.isPalindrome(nextCharIndex); | |
| } | |
| String.prototype.reverse = function() { | |
| return this.split('').reverse().join(''); | |
| } | |
| String.prototype.getMiddleCharIndex = function() { | |
| return Math.round(this.length/2); | |
| } | |
| String.prototype.middleSplit = function() { | |
| firstHalf = this.substr(0, this.getMiddleCharIndex()); | |
| secondHalf = this.substr(this.getMiddleCharIndex() - 1, this.length); | |
| return [firstHalf, secondHalf]; | |
| } | |
| String.prototype.isLapindrome = function() { | |
| const [firstHalf, secondHalf] = this.middleSplit(); | |
| return firstHalf === secondHalf.reverse(); | |
| } | |
| const inputStrings = ['mom', 'test', 'dad', 'factor', 'wise', 'racecar']; | |
| inputStrings.map(inputString => { | |
| console.log(`Q: Is '${inputString}' is palindrome?'`) | |
| console.log(`A: ${inputString.isPalindrome() ? 'Yes' : 'No'}!'`); | |
| console.log('--------'); | |
| console.log(`Q: Is '${inputString}' is lapindrome?'`) | |
| console.log(`A: ${inputString.isLapindrome() ? 'Yes' : 'No'}!'`); | |
| console.log('========'); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment