Collected Reusable JavaScript Utility Functions

Real-time Current Time Formatter

// Initialize immediately to avoid blank initial render
updateTimeDisplay();
// Refresh every 1 second
setInterval(updateTimeDisplay, 1000);

/**
 * Updates date and time display elements
 */
function updateTimeDisplay() {
  const yearEl = document.querySelector('.date-display .year');
  const monthEl = document.querySelector('.date-display .month');
  const dayEl = document.querySelector('.date-display .day');
  
  const hourEl = document.querySelector('.time-display .hour');
  const minuteEl = document.querySelector('.time-display .minute');
  const secondEl = document.querySelector('.time-display .second');

  const currentDate = new Date();
  const fullYear = currentDate.getFullYear();
  const month = String(currentDate.getMonth() + 1).padStart(2, '0');
  const day = String(currentDate.getDate()).padStart(2, '0');
  
  const hours = String(currentDate.getHours()).padStart(2, '0');
  const minutes = String(currentDate.getMinutes()).padStart(2, '0');
  const seconds = String(currentDate.getSeconds()).padStart(2, '0');

  yearEl.textContent = fullYear;
  monthEl.textContent = month;
  dayEl.textContent = day;

  hourEl.textContent = hours;
  minuteEl.textContent = minutes;
  secondEl.textContent = seconds;
}

Sample HTML Usage

<div class="date-display">
  Today is <span class="year">2024</span>年<span class="month">05</span>月<span class="day">20</span>日
</div>
<div class="time-display">
  Current time: <span class="hour">14</span>:<span class="minute">30</span>:<span class="second">45</span>
</div>

Countdown Timer

// Initialize and refresh every second
startCountdown();
setInterval(startCountdown, 1000);

/**
 * Renders countdown to a specified target datetime
 */
function startCountdown() {
  const hourElement = document.getElementById('countdown-hour');
  const minuteElement = document.getElementById('countdown-minute');
  const secondElement = document.getElementById('countdown-second');

  const currentTimestamp = Date.now();
  // Set your target datetime here
  const targetTimestamp = new Date('2024-12-31 23:59:59').getTime();
  const remainingSeconds = Math.max(0, (targetTimestamp - currentTimestamp) / 1000);

  const remainingHours = String(Math.floor(remainingSeconds / 3600)).padStart(2, '0');
  const remainingMinutes = String(Math.floor((remainingSeconds % 3600) / 60)).padStart(2, '0');
  const remainingSecondsFinal = String(Math.floor(remainingSeconds % 60)).padStart(2, '0');

  hourElement.textContent = remainingHours;
  minuteElement.textContent = remainingMinutes;
  secondElement.textContent = remainingSecondsFinal;
}

Sample HTML Usage

<div class="countdown-container">
  <h3>Event Countdown</h3>
  <div class="clock-display">
    <span id="countdown-hour">00</span>
    <span class="sep">:</span>
    <span id="countdown-minute">00</span>
    <span class="sep">:</span>
    <span id="countdown-second">00</span>
  </div>
</div>

Smooth Element Animation Utility

/**
 * Applies smooth transition animation to a DOM element
 * @param {HTMLElement} element - Target DOM element to animate
 * @param {number} targetPosition - Final left offset position
 * @param {Function} [callback] - Optional callback to run after animation completes
 */
function animateElement(element, targetPosition, callback) {
  // Clear any existing animation timers to prevent speed buildup
  clearInterval(element.animationTimer);
  
  element.animationTimer = setInterval(() => {
    // Calculate movement step, round properly for direction
    const moveStep = (targetPosition - element.offsetLeft) / 10;
    const adjustedStep = moveStep > 0 ? Math.ceil(moveStep) : Math.floor(moveStep);

    if (element.offsetLeft === targetPosition) {
      clearInterval(element.animationTimer);
      // Execute callback if provided
      if (typeof callback === 'function') callback();
    } else {
      element.style.left = `${element.offsetLeft + adjustedStep}px`;
    }
  }, 15);
}

Bubble Sort Algorithm

/**
 * Sorts an array using bubble sort algorithm
 * @param {Array} inputArray - Array to sort
 * @param {boolean} [descending=false] - Sort order, true for descending
 * @returns {Array} Sorted array
 */
function bubbleSort(inputArray, descending = false) {
  const arrayLength = inputArray.length;
  // Make copy to avoid mutating original array
  const workingArray = [...inputArray];

  for (let i = 0; i < arrayLength; i++) {
    for (let j = 0; j < arrayLength - i - 1; j++) {
      if (workingArray[j] > workingArray[j + 1]) {
        // Swap elements using destructuring assignment
        [workingArray[j], workingArray[j + 1]] = [workingArray[j + 1], workingArray[j]];
      }
    }
  }

  // Reverse if descending order is requested
  return descending ? workingArray.reverse() : workingArray;
}

Quick Sort Algorithm

/**
 * Sorts an array using quicksort algorithm
 * @param {Array} inputArray - Array to sort
 * @param {boolean} [descending=false] - Sort order, true for descending
 * @returns {Array} Sorted array
 */
function quickSort(inputArray, descending = false) {
  const arrayLength = inputArray.length;
  if (arrayLength <= 1) return inputArray;

  const pivot = inputArray[0];
  const leftPartition = [];
  const rightPartition = [];
  const pivotGroup = [];

  // Split array into pivot, left, and right groups
  for (const item of inputArray) {
    if (item === pivot) pivotGroup.push(item);
    else if (item > pivot) rightPartition.push(item);
    else leftPartition.push(item);
  }

  // Recursively sort sub-arrays
  const sortedLeft = bubbleSort(leftPartition);
  const sortedRight = bubbleSort(rightPartition);
  const finalArray = [...sortedLeft, ...pivotGroup, ...sortedRight];

  return descending ? finalArray.reverse() : finalArray;
}

Array Deduplication (ES5 Syntax)

/**
 * Removes duplicate values from an array using ES5 syntax
 * @param {Array} inputArray - Array with possible duplicates
 * @returns {Array} Array with unique values
 */
function deduplicateES5(inputArray) {
  const uniqueArray = [];
  for (const item of inputArray) {
    if (uniqueArray.indexOf(item) === -1) {
      uniqueArray.push(item);
    }
  }
  return uniqueArray;
}

Array Deduplication (ES6+)

/**
 * Removes duplicate values from an array using modern ES6+ syntax
 * @param {Array} inputArray - Array with possible duplicates
 * @returns {Array} Array with unique values
 */
function deduplicateES6(inputArray) {
  return [...new Set(inputArray)];
}

Remove Consecutive Character Duplicates

/**
 * Removes consecutive duplicate characters from a string
 * @param {string} inputString - Source string with consecutive duplicates
 * @returns {string} String with consecutive duplicates removed
 */
function removeConsecutiveDuplicates(inputString) {
  return inputString.replace(/(\w)\1+/g, '$1');
}

// Example usage
const testString = 'ijsisiiiisaajjdain';
const cleanedString = removeConsecutiveDuplicates(testString);
console.log(cleanedString); // Output: "ijsisaisjdain"

Range-based Random Number Generater

/**
 * Generates random numbers within a specified range
 * @param {number} min - Minimum value of random range
 * @param {number} max - Maximum value of random range
 * @param {number} [count] - Optional count of random numbers to return as array
 * @returns {number|Array} Single random number or array of random numbers
 */
function generateRandomNumbers(min, max, count) {
  /**
   * Gets a single random integer between min and max
   */
  function getRandomInRange() {
    return Math.floor(Math.random() * (max - min));
  }

  if (count) {
    const numberArray = [];
    for (let i = 0; i < count; i++) {
      numberArray.push(getRandomInRange());
    }
    return numberArray;
  } else {
    return getRandomInRange();
  }
}

Generate Custom Length Captcha

/**
 * Generates a captcha code of specified length
 * @param {number} length - Length of the captcha code
 * @param {boolean} [includeLetters=false] - Whether to include alphabetic characters
 * @returns {string} Generated captcha code
 */
function generateCaptcha(length, includeLetters = false) {
  if (!length) return 'Captcha length cannot be empty';

  const digitSet = '1234567890';
  const alphanumericSet = '1234567890qwertyuiopasdfghjklzxcvbnm';
  const characterSet = includeLetters ? alphanumericSet : digitSet;
  const setLength = characterSet.length;

  let captcha = '';
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * setLength);
    captcha += characterSet[randomIndex];
  }

  return captcha;
}

// Example usage
const testCaptcha = generateCaptcha(4, true);
console.log(testCaptcha);

Password Strength Checker

/**
 * Evaluates the strength of a given password
 * @param {string} password - Input password to evaluate
 * @returns {string} Password strength level or error message
 */
function checkPasswordStrength(password) {
  if (password.length < 6) return 'Please enter a password with at least 6 characters';

  let strengthLevel = 'Weak';
  const hasDigits = /[0-9]/.test(password);
  const hasLowercase = /[a-z]/.test(password);
  const hasUppercase = /[A-Z]/.test(password);
  const hasSpecialChars = /[.\-_]/.test(password);

  // Calculate strength based on character types present
  let strengthScore = 0;
  if (hasDigits) strengthScore++;
  if (hasLowercase) strengthScore++;
  if (hasUppercase) strengthScore++;
  if (hasSpecialChars) strengthScore++;

  switch(strengthScore) {
    case 1: strengthLevel = 'Weak'; break;
    case 2: strengthLevel = 'Medium'; break;
    case 3: strengthLevel = 'Strong'; break;
    case 4: strengthLevel = 'Very Strong'; break;
    default: strengthLevel = 'Weak';
  }

  return strengthLevel;
}

// Example usage
const testPassword = 'MyPass123!';
console.log(checkPasswordStrength(testPassword)); // Output: "Very Strong"

Email Validation with Regular Expression

/**
 * Validates if input string is a properly formatted email address
 * @param {string} email - Email address to validate
 * @returns {boolean} True if valid email, false otherwise
 */
function isValidEmail(email) {
  const emailRegex = /^([\w+\.])+@\w+([.]\w+)+$/;
  return emailRegex.test(email);
}

// Example usage
console.log(isValidEmail('test@example.com')); // true
console.log(isValidEmail('invalid-email')); // false

Tags: javascript Utility Functions Date Formatting Countdown Timer DOM Manipulation

Posted on Fri, 08 May 2026 04:32:43 +0000 by landavia