Skip to content

Instantly share code, notes, and snippets.

@PetukhovArt
Created January 2, 2025 09:49
Show Gist options
  • Save PetukhovArt/abd13166f0a1b770f3eece8c96c997ee to your computer and use it in GitHub Desktop.
Save PetukhovArt/abd13166f0a1b770f3eece8c96c997ee to your computer and use it in GitHub Desktop.
// Нужно написать функцию, которая проверит читается ли строка одинаково в обоих направлениях
// (без учета пробелов и знаков препинания)
// попробуйте решить несколькими способами
const isPalindrome1 = (str) => {
const punctuation = ' ,.;'
const arr = str.toLowerCase().split('')
.filter(ch => !punctuation.includes(ch))
const reversedArr = arr.toReversed()
let result = true
arr.forEach((el, idx) => {
if (el !== reversedArr[idx]) {
result = false
}
}
)
return result
}
const isPalindrome2 = (str) => {
const punctuation = ' ,.;'
const arr = str.toLowerCase().split('')
.filter(ch => !punctuation.includes(ch))
const isEven = (arr.length % 2) === 0
let count = 0
const middleIndex = !isEven ? Math.ceil(arr.length / 2) - 1 : null
for (let i = 0; i < arr.length; i++) {
const tryChangeCount = () => {
if (arr[i] === arr[arr.length - i - 1]) {
count++
}
}
if (middleIndex !== null) {
if (middleIndex === i) {
count++
} else {
tryChangeCount()
}
} else {
tryChangeCount()
}
}
return count === arr.length
}
const isPalindrome = (str) => {
const s = str.toLowerCase().replace(/[^a-zа-яё0-9]/g, '')
const reversed = s.split('').reverse().join('')
return s === reversed
}
console.log(isPalindrome('топот')); // true
console.log(isPalindrome('л')); // true
console.log(isPalindrome('абвгвбж')); //false
console.log(isPalindrome('А муза рада музе без ума да разума')); // true
console.log(isPalindrome('а роза упала на лапу Азора')); // true
console.log(isPalindrome('1')); //true
console.log(isPalindrome('91019')); //true
console.log(isPalindrome('22.02.2022')); //true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment