generate a random 12 digit string that reads the same forward as backwards. in javascript

Here's a code snippet that generates a random 12-digit string that is a palindrome:

index.tsx
function generatePalindrome() {
  const chars = "0123456789";
  let result = "";
  
  // Generate the first 6 characters at random
  for (let i = 0; i < 6; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    result += chars[randomIndex];
  }
  
  // Generate the last 6 characters by copying the first 6 characters in reverse
  result += result.split("").reverse().join("");
  
  return result;
}
422 chars
16 lines

This function uses a string of possible characters, 0123456789, to generate a random string. It then generates the first 6 characters by selecting a random index from this string and adding the corresponding character to the result, repeating this process 6 times. The last 6 characters are then generated by splitting the first 6 characters into an array of characters, reversing that array, and joining the result back into a string. The resulting string is the concatenation of the first 6 characters and the reversed last 6 characters, creating a 12-digit palindrome.

Here's an example output of this function:

index.tsx
generatePalindrome(); // "165133512531"
40 chars
2 lines

gistlibby LogSnag