Last active
January 4, 2022 12:29
-
-
Save leandronsp/46c31eb9e0e31c03fefefa994ebd97d7 to your computer and use it in GitHub Desktop.
Palindromes of X random words
This file contains 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
/* | |
Reverse a word | |
*/ | |
const reverse = (word) => { | |
const letters = word.split('') | |
const lastIdx = letters.length - 1 | |
return letters | |
.map((letter, idx) => { return letters[lastIdx - idx] }) | |
.join('') | |
} | |
/* | |
Check if a word is palindrome | |
*/ | |
const isPalindrome = (word) => { | |
return word === reverse(word) | |
} | |
/* | |
A random number up to a limit | |
*/ | |
const randomMax = (sizeLimit) => { | |
return Math.floor( | |
Math.random() * sizeLimit | |
) | |
} | |
/* | |
Pick a sample from a list | |
*/ | |
const sample = (list) => { | |
const randomIdx = randomMax(list.length) | |
return list[randomIdx] | |
} | |
/* | |
A simple series iterator | |
*/ | |
const iterateTimes = (times) => { | |
return Array.from(Array(times).keys()) | |
} | |
/* | |
A random word from 3 to 5 characters | |
*/ | |
const randomWord = () => { | |
const alphabet = 'abcdefghijklmnopqrstuvxz'.split('') | |
const size = sample([3, 4, 5]) | |
return iterateTimes(size) | |
.reduce((acc) => { return acc.concat(sample(alphabet)) }, '') | |
} | |
/* | |
Filter all palindromes of X random words | |
*/ | |
const palindromesFrom = (limit) => { | |
return iterateTimes(limit) | |
.map(() => { return randomWord() }) | |
.filter((word) => { return isPalindrome(word) }) | |
} | |
console.log(reverse('leandro')) | |
console.log(isPalindrome('leandro')) | |
console.log(isPalindrome('ana')) | |
console.log(sample([3, 4, 5])) | |
console.log(randomWord()) | |
console.log(palindromesFrom(1000)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment