This Repository is made for the use of reusable functions in javascript which we can use to simplify our work for making web app.
- Reusable Javascript Utility Functions
- Table of Contents
- 1. Array Utility
- 2. Date And Time Utility
- 3. DOM Utility
- 4. Event Utility
- 5. File Utility
- 6. Formatting Utility
- 7. Handling Promises Utility
- 8. Local Storage Utility
- 9. Number Utility
- 10. Object Utility
- 11. Security Utility
- 12. String Utility
- 13. URL Utility
- 13.1 Parse URL
- 14.Validation Utility
- 14.1 Aadhaar Validation
- 14.2 Address Validation
- 14.3 Bank Account Number Validation
- 14.4 Credit Card Validation
- 14.5 Debit Card Validation
- 14.6 Driving License Validation
- 14.7 Email Validation
- 14.8 IFSC Code Validation
- 14.9 Mobile Number Validation
- 14.10 Passport Number Validation
- 14.11 URL Validation
In this we will see all the array utility functions in javascript.
Randomly shuffles the elements of an array.
//Randomly shuffles the elements of an 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;
}
console.log(shuffleArray([1, 2, 3, 4, 5])); // [3, 2, 5, 1, 4]
Splits an array into chunks of a specified size.
//Splits an array into chunks of a specified size
function chunkArray(arr, size) {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
console.log(chunkArray([1, 2, 3, 4, 5], 2)); // [[1, 2], [3, 4], [5]]
Flattens a nested array into a single array.
//Flattens a nested array into a single array
function flattenArray(arr) {
return arr.flat(Infinity);
}
console.log(flattenArray([1, [2, [3, [4, 5]]]])); // [1, 2, 3, 4, 5]
Returns only the unique elements from an array.
//Returns only the unique elements from an array
function uniqueArray(arr) {
return [...new Set(arr)];
}
console.log(uniqueArray([1, 2, 2, 3, 4, 4, 5])); // [1, 2, 3, 4, 5]
In this we will see all the Date & Time utility functions in javascript.
Adds or subtracts a number of days from a date.
//Adds or subtracts a number of days from a date
function addDays(date, days) {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
console.log(addDays(new Date(), 7)); // 7 days from now
Formats a time in milliseconds to hh:mm:ss
.
//Formats a time in milliseconds to `hh:mm:ss`
function formatTime(ms) {
const hours = Math.floor(ms / 3600000);
const minutes = Math.floor((ms % 3600000) / 60000);
const seconds = Math.floor((ms % 60000) / 1000);
return `${hours}:${minutes}:${seconds}`;
}
console.log(formatTime(1000)); // 0:0:1
Displays how long ago a date was (e.g., "5 minutes ago").
//Displays how long ago a date was (e.g., "5 minutes ago")
function timeAgo(date) {
const now = new Date();
const seconds = Math.floor((now - date) / 1000);
let interval = Math.floor(seconds / 31536000);
if (interval >= 1) return `${interval} year${interval > 1 ? 's' : ''} ago`;
interval = Math.floor(seconds / 2592000);
if (interval >= 1) return `${interval} month${interval > 1 ? 's' : ''} ago`;
interval = Math.floor(seconds / 86400);
if (interval >= 1) return `${interval} day${interval > 1 ? 's' : ''} ago`;
interval = Math.floor(seconds / 3600);
if (interval >= 1) return `${interval} hour${interval > 1 ? 's' : ''} ago`;
interval = Math.floor(seconds / 60);
if (interval >= 1) return `${interval} minute${interval > 1 ? 's' : ''} ago`;
return `${seconds} seconds ago`;
}
console.log(timeAgo(new Date(Date.now() - 1000))); // 1 second ago
In this we will see all the DOM utility functions in javascript.
Creates a new DOM element with optional attributes.
//Creates a new DOM element with optional attributes
function createElement(tag, attributes = {}) {
const element = document.createElement(tag);
Object.keys(attributes).forEach(key => element.setAttribute(key, attributes[key]));
return element;
}
console.log(createElement('a', { href: 'https://w3docs.com' })); // <a href="https://w3docs.com"></a>
Smoothly scrolls to a specific element in the DOM.
//Smoothly scrolls to a specific element in the DOM
function scrollToElement(selector) {
document.querySelector(selector).scrollIntoView({ behavior: 'smooth' });
}
console.log(scrollToElement('#section-2')); // Scrolls to an element with the ID of 'section-2'
Toggles a class on a DOM element.
//Toggles a class on a DOM element
function toggleClass(element, className) {
element.classList.toggle(className);
}
console.log(toggleClass(document.getElementById('my-element'), 'active'));
In this we will see all the Event utility functions in javascript.
Delegates an event to a parent element, useful for dynamic content.
//Delegates an event to a parent element, useful for dynamic content
function delegateEvent(parent, eventType, selector, handler) {
parent.addEventListener(eventType, event => {
if (event.target.matches(selector)) {
handler(event);
}
});
}
console.log(delegateEvent(document.body, 'click', 'button', event => console.log('Button clicked!')));
// logs the clicked <a> element in the console
In this we will see all the File utility functions in javascript.
Triggers a download of a file in the browser.
//Triggers a download of a file in the browser
function downloadFile(data, filename, type) {
const file = new Blob([data], { type });
const a = document.createElement('a');
const url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
console.log(downloadFile('Hello, world!', 'hello.txt', 'text/plain')); // Downloads a file with the content 'Hello, world!' as 'hello.txt'
In this we will see all the Formatting utility functions in javascript.
formates a currency.
function formatCurrency(number, locale = 'en-US', currency = 'USD') {
const formatter = new Intl.NumberFormat(locale, {
style: 'currency',
currency,
});
return formatter.format(number);
}
console.log(formatCurrency(1000,'en-US','INR')); //₹1,000.00
formates a date.
function formatDate(date, locale = 'en-US', options = {}) {
const formatter = new Intl.DateTimeFormat(locale, options);
return formatter.format(date);
}
console.log(formatDate(new Date())); // 8/16/2024
formates a email.
function formatEmail(email) {
if (!email.includes('@')) {
throw new Error('Invalid email format');
}
const normalizedEmail = email.toLowerCase();
const formattedEmail = normalizedEmail.trim();
return formattedEmail;
}
console.log(formatEmail('[email protected]')); // amit@example.com
formates a time.
function formatTime(date, locale = 'en-US', options = {}) {
const timeOptions = {
...options,
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
};
const formatter = new Intl.DateTimeFormat(locale, timeOptions);
return formatter.format(date);
}
console.log(formatTime(new Date())); // 12:00:00 AM
In this we will see all the Handling Promises utility functions in javascript.
Retries a promise-based function a specified number of times.
//Retries a promise-based function a specified number of times
function retryPromise(fn, retries) {
return fn().catch(err => {
if (retries > 0) {
return retryPromise(fn, retries - 1);
} else {
throw err;
}
});
}
console.log(retryPromise(() => Promise.reject("Error"), 3)); // Error
In this we will see all the Local Storage utility functions in javascript.
Sets an item in local storage with JSON stringification.
//Sets an item in local storage with JSON stringification
function setLocalStorageItem(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
console.log(setLocalStorageItem('user', { name: 'John', age: 30 })); // undefined
Gets an item from local storage and parses it as JSON.
//Gets an item from local storage and parses it as JSON
function getLocalStorageItem(key) {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : null;
}
console.log(getLocalStorageItem('user')); // { name: 'John', age: 30 }
Removes an item from local storage.
//Removes an item from local storage
function removeLocalStorageItem(key) {
localStorage.removeItem(key);
}
console.log(removeLocalStorageItem('user')); // undefined
In this Utility we will work with numbers.
Clamps a number between a minimum and maximum value.
//Clamps a number between a minimum and maximum value
function clampNumber(num, min, max) {
return Math.min(Math.max(num, min), max);
}
console.log(clampNumber(3, 0, 4)); // 3
Generates a random number between two values.
//Generates a random number between two values
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomNumber(1, 10)); // 4
Rounds a number to a specified number of decimal places.
//Rounds a number to a specified number of decimal places
function roundToDecimal(num, places) {
const factor = Math.pow(10, places);
return Math.round(num * factor) / factor;
}
console.log(roundToDecimal(1.23456, 2)); // 1.23
In this Utility we will work with objects.
Recursively freezes an object to make it immutable.
//Recursively freezes an object to make it immutable
function deepFreeze(obj) {
Object.keys(obj).forEach(prop => {
if (typeof obj[prop] === 'object' && obj[prop] !== null) {
deepFreeze(obj[prop]);
}
});
return Object.freeze(obj);
}
console.log(deepFreeze({ a: 1, b: { c: 2 } })); // { a: 1, b: { c: 2 } }
Safely retrieves a nested value from an object.
//Safely retrieves a nested value from an object
function getNestedValue(obj, keyPath) {
return keyPath.reduce((acc, key) => acc && acc[key], obj);
}
console.log(getNestedValue({ a: { b: { c: 1 } } }, ['a', 'b', 'c'])); // 1
Merges two or more objects together.
//Merges two or more objects together
function mergeObjects(...objects) {
return Object.assign({}, ...objects);
}
console.log(mergeObjects({ a: 1 }, { b: 2 })); // { a: 1, b: 2 }
Converts an object to a query string.
//Converts an object to a query string
function objectToQueryString(obj) {
return Object.keys(obj).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`).join('&');
}
console.log(objectToQueryString({ a: 1, b: 2 })); // "a=1&b=2"
In this Utility we will work with security.
Escapes HTML to prevent XSS attacks.
// /Escapes HTML to prevent XSS attacks
function escapeHTML(str) {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
console.log(escapeHTML("<a href='#'>Hello World</a>")); // "<a href='#'>Hello World</a>"
In this Utility we will work with string.
Counts the number of occurrences of a specific character in a string.
//Counts the number of occurrences of a specific character in a string
function countCharacter(str, char) {
return str.split(char).length - 1;
}
console.log(countCharacter("Hello World", "l")); // 3
Converts a string into a URL-friendly "slug".
// Converts a string into a URL-friendly "slug"
function slugify(str) {
return str.toLowerCase().trim().replace(/\s+/g, '-').replace(/[^\w\-]+/g, '');
}
console.log(slugify(" Hello World ")); // "hello-world"
Reverses a given string.
// Reverses a given string
function reverseString(str) {
return str.split('').reverse().join('');
}
console.log(reverseString("Hello World")); // "dlroW olleH"
Trims whitespace from the start and end of a string.
// Trims whitespace from the start and end of a string
function trimString(str) {
return str.trim();
}
console.log(trimString(" Hello World ")); // "Hello World"
In this Utility we will work with url.
Parses a URL into its components.
//Parses a URL into its components
function parseURL(url) {
const a = document.createElement('a');
a.href = url;
return {
protocol: a.protocol,
hostname: a.hostname,
port: a.port,
pathname: a.pathname,
search: a.search,
hash: a.hash,
host: a.host
};
}
console.log(parseURL('https://w3docs.com/path/name?search=test#hash')); // {protocol: "https:", hostname: "w3docs.com", port: "", pathname: "/path/name", search: "?search=test", hash: "#hash", host: "w3docs.com"}
Updates a query string parameter in the URL without reloading the page.
//Updates a query string parameter in the URL without reloading the page
function updateQueryStringParameter(key, value) {
const url = new URL(window.location);
url.searchParams.set(key, value);
window.history.pushState({}, '', url);
}
console.log(updateQueryStringParameter('page', 2)); // Updates '?page=2' in the URL
In this Utility we will work with Validator.
Regular expression for validating an Aadhaar number.
// Regular expression for validating an Aadhaar number
function validateAadhaarCard(aadhaarNumber) {
const aadhaarRegex = /^\d{12}$/;
return aadhaarRegex.test(aadhaarNumber);
}
console.log(validateAadhaarCard('123456789012')); // true
Regular expression for validating a global address.
// Regular expression for validating a global address
function validateGlobalAddress(address) {
const globalAddressRegex = /^[a-zA-Z0-9\s,.-/()#'&]+$/;
return globalAddressRegex.test(address);
}
console.log(validateGlobalAddress('123, Main Street')); // true
Regular expression for validating an Indian bank account number.
// Regular expression for validating an Indian bank account number
function validateBankAccountNumber(accountNumber) {
const accountNumberRegex = /^\d{9,18}$/;
return accountNumberRegex.test(accountNumber);
}
console.log(validateBankAccountNumber('1234567890123456')); // true
Algorithm for Credit Card Validation.
function luhnAlgorithm(cardNumber) {
let sum = 0;
let shouldDouble = false;
// Loop through the card number digits starting from the right
for (let i = cardNumber.length - 1; i >= 0; i--) {
let digit = parseInt(cardNumber[i]);
if (shouldDouble) {
digit *= 2;
if (digit > 9) {
digit -= 9;
}
}
sum += digit;
shouldDouble = !shouldDouble;
}
// If the total modulo 10 is 0, the card number is valid
return sum % 10 === 0;
}
function validateCreditCardNumber(creditCardNumber) {
creditCardNumber = creditCardNumber.replace(/\D/g, '');
if (creditCardNumber.length < 13 || creditCardNumber.length > 19) {
return false;
}
return luhnAlgorithm(creditCardNumber);
}
console.log(validateCreditCardNumber('123456789011')); // false
Algorithm for Debit Card Validation.
function luhnAlgorithm(cardNumber) {
let sum = 0;
let shouldDouble = false;
// Loop through the card number digits starting from the right
for (let i = cardNumber.length - 1; i >= 0; i--) {
let digit = parseInt(cardNumber[i]);
if (shouldDouble) {
digit *= 2;
if (digit > 9) {
digit -= 9;
}
}
sum += digit;
shouldDouble = !shouldDouble;
}
// If the total modulo 10 is 0, the card number is valid
return sum % 10 === 0;
}
function validateDebitCardNumber(debitCardNumber) {
debitCardNumber = debitCardNumber.replace(/\D/g, '');
if (debitCardNumber.length !== 16) {
return false;
}
return luhnAlgorithm(debitCardNumber);
}
console.log(validateDebitCardNumber('1234567890123456')); // true
Regular expression for validating an Indian driving license.
// Regular expression for validating an Indian driving license
function validateDrivingLicense(licenseNumber) {
const licenseRegex = /^[A-Z]{2}[0-9]{2}[0-9]{4}[0-9]{7}$/;
return licenseRegex.test(licenseNumber);
}
console.log(validateDrivingLicense('KA1234567890123')); // true
Regular expression for validating an email.
// Regular expression for validating an email
function validateEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
console.log(validateEmail('[email protected]')); // true
Regular expression for validating IFSC code.
// Regular expression for validating IFSC code
function validateIFSC(ifsc) {
const ifscRegex = /^[A-Z]{4}0[A-Z0-9]{6}$/;
return ifscRegex.test(ifsc);
}
console.log(validateIFSC('SBIN0001234')); // true
Regular expression for validating an Indian mobile number.
// Regular expression for validating an Indian mobile number
function validateMobileNumber(mobileNumber) {
const mobileRegex = /^[6-9]\d{9}$/;
return mobileRegex.test(mobileNumber);
}
console.log(validateMobileNumber('1234567890')); // false
Regular expression for validating an Indian passport number.
// Regular expression for validating an Indian passport number
function validatePassportNumber(passportNumber) {
const passportRegex = /^[A-Z][0-9]{7}$/;
return passportRegex.test(passportNumber);
}
console.log(validatePassportNumber('A1234567')); // true
Regular expression for validating a URL.
// Regular expression for validating a URL
function validateURL(url) {
const urlRegex = /^(https?:\/\/)?([\w-]+(\.[\w-]+)+)([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?$/;
return urlRegex.test(url);
}
console.log(validateURL('https://www.google.com')); // true