Skip to main content
/**
 * This function checks if a given string is a palindrome.
 * A palindrome is a word, phrase, or sequence that reads the same forward as backward.
 *
 * @param {string} str - The input string to check.
 * @returns {boolean} - True if the string is a palindrome, false otherwise.
 */
function isPalindrome(str) {
  // Remove non-alphanumeric characters and convert to lowercase
  const cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();

  // Compare the string with its reversed version
  return cleanStr === cleanStr.split('').reverse().join('');
}

/**
 * This function calculates the factorial of a given number.
 * The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.
 *
 * @param {number} n - The number to calculate the factorial of.
 * @returns {number} - The factorial of n.
 */
function factorial(n) {
  if (n === 0) {
    return 1; // Base case: factorial of 0 is 1
  } else {
    return n * factorial(n - 1); // Recursive step
  }
}

/**
 * This function checks if a given number is prime.
 * A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
 *
 * @param {number} num - The number to check for primality.
 * @returns {boolean} - True if the number is prime, false otherwise.
 */
function isPrime(num) {
  if (num <= 1) {
    return false; // Numbers less than or equal to 1 are not prime
  }
  for (let i = 2; i <= Math.sqrt(num); i++) {
    if (num % i === 0) {
      return false; // If divisible by any number other than 1 and itself, it's not prime
    }
  }
  return true;
}

/**
 * This function generates a random number between a specified minimum and maximum value (inclusive).
 *
 * @param {number} min - The minimum value (inclusive).
 * @param {number} max - The maximum value (inclusive).
 * @returns {number} - A random number between min and max.
 */
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

/**
 * This function shuffles an array in place using the Fisher-Yates (Knuth) shuffle algorithm.
 *
 * @param {array} array - The array to shuffle.
 * @returns {array} - The shuffled array.
 */
function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

These functions demonstrate some common and useful JavaScript utilities:

  • isPalindrome(): Checks for palindromes.
  • factorial(): Calculates the factorial of a number.
  • isPrime(): Determines if a number is prime.
  • getRandomInt(): Generates random integers within a specified range.
  • shuffleArray(): Shuffles the elements of an array in place.

You can use these functions directly in your projects or adapt them to your specific needs.