Essential JavaScript Utilities and Methods

Dynamic Current Time Display

Display current time with year, month, day, hours, minutes, seconds, and day of week using padStart() for consistent formatting:

const timeInterval = setInterval(() => {
    const currentTime = new Date();
    const year = currentTime.getFullYear();
    const month = String(currentTime.getMonth() + 1).padStart(2, '0');
    const day = String(currentTime.getDate()).padStart(2, '0');
    const hours = String(currentTime.getHours()).padStart(2, '0');
    const minutes = String(currentTime.getMinutes()).padStart(2, '0');
    const seconds = String(currentTime.getSeconds()).padStart(2, '0');
    const weekDay = currentTime.getDay();
    const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
    const formattedTime = `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds} 星期${weekDays[weekDay]}`;
    console.log(formattedTime);
}, 1000);

Color Utilities

Convert Hex to RGBA

function hexToRgba(hexColor, opacity = 1) {
    // Validate input format
    if (!/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(hexColor)) {
        throw new Error('Invalid hexadecimal color code!');
    }
    
    // Parse hex color components
    let r = parseInt(hexColor.slice(1, 3), 16);
    let g = parseInt(hexColor.slice(3, 5), 16);
    let b = parseInt(hexColor.slice(5, 7), 16);
    
    // Return RGBA color string
    return `rgba(${r}, ${g}, ${b}, ${opacity})`;
}

Generate Random Hex Color

function generateRandomColor() {
    const hexDigits = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += hexDigits[Math.floor(Math.random() * 16)];
    }
    return color;
}

Array Methods

forEach()

Iterate through each element in an array:

myArray.forEach((element, index, array) => {
    // element: current item
    // index: position of current item
    // array: original array
    // Processing logic here
});

map()

Create a new array by transforming each element:

const newArray = myArray.map((element, index, array) => {
    // Return transformed value for each element
    return element * 2;
});

includes()

Check if array contains a specific element:

const containsValue = myArray.includes('targetValue');

indexOf()

Find the index of the first occurrence of an element:

const elementIndex = myArray.indexOf('targetValue');

some()

Check if at least one element meets a condition:

const hasMatchingElement = myArray.some(item => {
    return item.property === targetValue;
});

every()

Check if all elements meet a condition:

const allMatch = myArray.every(item => {
    return item.property === targetValue;
});

find()

Find the first element that meets a condition:

const foundElement = myArray.find(item => {
    return item.property === targetValue;
});

findIndex()

Find the index of the first element that meets a condition:

const foundIndex = myArray.findIndex(item => {
    return item.property === targetValue;
});

filter()

Create a new array with elements that meet a condition:

const filteredArray = myArray.filter(item => {
    return item.property > thresholdValue;
});

reduce()

Reduce array to a single value:

const sum = myArray.reduce((accumulator, currentValue, index, array) => {
    return accumulator + currentValue;
}, initialValue);

for...in

Loop through object properties or array indices:

for (const key in object) {
    // key: property name or array index
    // object[key]: property value
}

for...of

Loop through array values:

for (const value of array) {
    // value: array element
}

sort()

Sort numeric arrays:

// Ascending order
myArray.sort((a, b) => a - b);

// Descending order
myArray.sort((a, b) => b - a);

Set for Deduplication

Remove duplicates from an array:

const uniqueArray = [...new Set(myArray)];

Object.assign()

Convert array to object:

const objectFromArray = Object.assign({}, myArray);

Object Methods

Object.keys()

Get object property names as an array:

const propertyNames = Object.keys(myObject);

Object.values()

Get object property values as an array:

const propertyValues = Object.values(myObject);

Object.entries()

Convert object to array of key-value pairs:

const keyValuePairs = Object.entries(myObject);

Regular Expressions

Remove Whitespace

text.replace(/\s+/g, "");

Remove HTML Tags

text.replace(/<\/?[a-z][^>]*>/gi, '');

Allow Only Numbers in Input

inputValue.replace(/[^0-9]/g, "");

Remove Letters

text.replace(/[a-zA-Z]/g, "");

AJAX Operations

Fetch for Form Data

Properly submit form data using FormData:

const formData = new FormData();
formData.append('fieldName', 'value');

fetch('api/endpoint', {
    method: 'POST',
    body: formData
})
.then(response => response.())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Axios for Form Data

Submit form data using Axios:

const formData = new FormData();
formData.append('fieldName', 'value');

axios({
    url: 'api/endpoint',
    method: 'post',
    data: formData,
    headers: {
        'Content-Type': 'multipart/form-data'
    }
})
.then(response => {
    console.log(response.data);
})
.catch(error => {
    console.error('Error submitting form:', error);
});

Debouncing and Throttling

Debounce Function

/**
 * Creates a debounced function that delays invoking until after wait milliseconds have elapsed
 * @param {Function} func - Function to debounce
 * @param {number} wait - Millisecond delay
 * @returns {Function} - Debounced function
 */
export function debounce(func, wait) {
    let timeoutId;
    return function(...args) {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => func.apply(this, args), wait);
    };
}

Throttle Function

/**
 * Creates a throttled function that only invokes at most once per every wait milliseconds
 * @param {Function} func - Function to throttle
 * @param {number} limit - Millisecond limit between calls
 * @returns {Function} - Throttled function
 */
export function throttle(func, limit) {
    let inThrottle;
    return function(...args) {
        if (!inThrottle) {
            func.apply(this, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

Usage Example

import { debounce, throttle } from './utilities';

// Throttled function call
const throttledFunction = throttle(() => {
    // Function logic here
}, 1000);

// Debounced function call
const debouncedFunction = debounce(() => {
    // Function logic here
}, 500);

Tags: javascript programming web development Utilities Methods

Posted on Wed, 02 Sep 2026 16:41:00 +0000 by doobster