Skip to content

Instantly share code, notes, and snippets.

@salvatorecapolupo
Created February 22, 2022 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save salvatorecapolupo/a62c17f67140eb15a136b47f451c968a to your computer and use it in GitHub Desktop.
Save salvatorecapolupo/a62c17f67140eb15a136b47f451c968a to your computer and use it in GitHub Desktop.
Palyndrome dates generator (Javascript)
function palindrome(str) {
// Step 1. Lowercase the string and use the RegExp to remove unwanted characters from it
var re = /[\W_]/g; // or var re = /[^A-Za-z0-9]/g;
var lowRegStr = str.toLowerCase().replace(re, '');
// str.toLowerCase() = "A man, a plan, a canal. Panama".toLowerCase() = "a man, a plan, a canal. panama"
// str.replace(/[\W_]/g, '') = "a man, a plan, a canal. panama".replace(/[\W_]/g, '') = "amanaplanacanalpanama"
// var lowRegStr = "amanaplanacanalpanama";
// Step 2. Use the same chaining methods with built-in functions from the previous article 'Three Ways to Reverse a String in JavaScript'
var reverseStr = lowRegStr.split('').reverse().join('');
// lowRegStr.split('') = "amanaplanacanalpanama".split('') = ["a", "m", "a", "n", "a", "p", "l", "a", "n", "a", "c", "a", "n", "a", "l", "p", "a", "n", "a", "m", "a"]
// ["a", "m", "a", "n", "a", "p", "l", "a", "n", "a", "c", "a", "n", "a", "l", "p", "a", "n", "a", "m", "a"].reverse() = ["a", "m", "a", "n", "a", "p", "l", "a", "n", "a", "c", "a", "n", "a", "l", "p", "a", "n", "a", "m", "a"]
// ["a", "m", "a", "n", "a", "p", "l", "a", "n", "a", "c", "a", "n", "a", "l", "p", "a", "n", "a", "m", "a"].join('') = "amanaplanacanalpanama"
// So, "amanaplanacanalpanama".split('').reverse().join('') = "amanaplanacanalpanama";
// And, var reverseStr = "amanaplanacanalpanama";
// Step 3. Check if reverseStr is strictly equals to lowRegStr and return a Boolean
return reverseStr === lowRegStr; // "amanaplanacanalpanama" === "amanaplanacanalpanama"? => true
}
// Returns an array of dates between the two dates
function getDates (startDate, endDate) {
const dates = []
let currentDate = startDate
const addDays = function (days) {
const date = new Date(this.valueOf())
date.setDate(date.getDate() + days)
return date
}
while (currentDate <= endDate) {
dates.push(currentDate)
currentDate = addDays.call(currentDate, 1)
}
return dates
}
function padTo2Digits(num) {
return num.toString().padStart(2, '0');
}
function formatDate(date) {
return [
padTo2Digits(date.getDate()),
padTo2Digits(date.getMonth() + 1),
date.getFullYear(),
].join('/');
}
const dates = getDates(new Date(2022, 02, 22), new Date(3001, 03, 10))
dates.forEach(function (date) {
if ( palindrome( formatDate(date) ) )
console.log( formatDate(date) );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment