react-js-plugins
Version:
A powerful and efficient React utility library designed to enhance application performance by streamlining and simplifying the management of complex asynchronous operations.
1,633 lines (1,319 loc) • 36.5 kB
Markdown
**react-js-plugins** package is a lightweight and powerful toolkit for developers, providing reusable solutions for various application requirements. react-js-plugins offers a comprehensive collection of utility functions designed to simplify common development tasks. Key functionalities include form validation, date formatting, array/object manipulation, and exporting data to Excel. Additional features include browser/device detection, storage management, reducers, performance optimization utilities, and string/number formatting tools.
**Note: This lightweight and type-safe package is written in TypeScript and offers full support for all utilities across all modern browsers.**
### **Installation**
Install the package:
```bash
npm install react-js-plugins
# or
pnpm add react-js-plugins
```
### **Authors**
    
### **Browser Support**
|  |  |  |  | 
| ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ |
### **Features**
Here's the properly structured documentation with clear purpose explanations:
✅ **_log**
Logs a styled message to the console with a specified log level (`log`, `info`, `warn`, `error`).
```ts
// 📝 Custom log with style
_log("UserService", "Fetching user details...", "info");
```
✅ **_handleApi**
Wraps an API call with success and error handling, executing the appropriate callback based on the result.
```ts
_handleApi(
getDetails({ name: 'sia' }),
(res) => console.log(res),
(err) => console.error(err)
);
```
✅ **_copyText**
Copies the provided text to the clipboard, using modern APIs with a fallback for older browsers.
```ts
// 📋 Copy Text
const success = await _copyText("Hello, clipboard!");
if (success) {
console.log("Text copied successfully");
}
```
✅ **_pasteText**
Retrieves and returns the current text content from the clipboard, using modern APIs with a fallback for older browsers.
```ts
// 📥 Paste Text
const text = await _pasteText();
if (text) {
console.log("Pasted text:", text);
}
```
✅ **_alert**
Shows a customizable alert modal.
```ts
// 🚨 Alert Dialog
await _alert({ title: "Test", text: "Data save successfully!" });
```
✅ **_confirm**
Shows a customizable confirm modal.
```ts
const confirmed = await _confirm({
title: "Are you sure?",
text: "Do you really want to delete this item?",
icon: "warning",
confirmButtonText: "Yes, delete it",
cancelButtonText: "No, cancel",
});
if (confirmed) {
// proceed with delete
} else {
// cancelled
}
```
### ✅ **_generateUUID**
Generates a unique UUID string using the browser's `crypto` API.
```ts
// Example usage
const id = _generateUUID();
console.log(id); // e.g., "3b12f1df-5232-4e6b-8f36-3a4e5f7f8b84"
```
✅ **_throwError**
Throws an error with an optional context object and logs it to the console.
```ts
// ❌ Throw an error
_throwError("Something went wrong",);
```
✅ **_encodeURI**
Encodes a URI component by escaping special characters to make it safe for use in URLs.
```ts
const encoded = _encodeURI('hello world@2024');
// Output: 'hello%20world%402024'
```
✅ **_decodeURI**
Decodes an encoded URI component back to its original readable string format.
```ts
const decoded = _decodeURI('hello%20world%402024');
// Output: 'hello world@2024'
```
✅ **_encryptJson**
Encrypts a JSON object using AES encryption with a secret key.
```ts
// 🔐 Encrypt JSON
const encrypted = _encryptJson({ name: "John" }, "secret123");
```
✅ **_decryptJson**
Decrypts AES-encrypted JSON string using a secret key.
```ts
// 🔓 Decrypt JSON
const decrypted = _decryptJson(encryptedString, "secret123");
```
✅ **_encryptString**
Encrypts a plain string using AES encryption, with optional random IV.
```ts
// 🔐 Encrypt String
const result = _encryptString("mySecretText", "secretKey");
```
✅ **_decryptString**
Decrypts an AES-encrypted string using the provided IV and secret key.
```ts
// 🔓 Decrypt String
const plainText = _decryptString(ciphertext, iv, "secretKey");
```
✅ **_encryptPayload**
Encrypts a full payload using a randomly generated key and IV, secured by a static key.
```ts
// 🔐 Encrypt Payload
const payload = _encryptPayload({ id: 1 }, "mainSecretKey");
```
✅ **_downloadBlob**
Triggers download of a Blob object.
```ts
_downloadBlob(blob, 'myfile.pdf');
```
✅ **_fileToBase64**
Converts a file to a base64-encoded string.
```ts
const base64 = await _fileToBase64(file);
```
✅ **_base64ToBlob**
Converts a base64-encoded string into a Blob object.
```ts
const blob = _base64ToBlob(base64String);
```
✅ **_downloadBase64File**
This function allows downloading any base64-encoded data as a file with a specified filename and extension.
```ts
const base64Image = 'iVBORw0KGgoAAAANSUhEUgAAA...';
downloadBase64File(base64Image, 'my-picture.png');
const base64ImageWithPrefix = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA...';
downloadBase64File(base64ImageWithPrefix, 'my-picture.png');
const base64PDF = 'JVBERi0xLjQKJeLjz9MNCjEgMCBvYmoK...';
downloadBase64File(base64PDF, 'invoice.pdf');
const base64PDFWithPrefix = 'data:application/pdf;base64,JVBERi0xLjQKJeLjz9MNCjEgMCBvYmoK...';
downloadBase64File(base64PDFWithPrefix, 'invoice.pdf');
```
✅ **_dynamicReducer**
Creates a simple dynamic reducer using generic action handler logic.
```ts
// 🧠 Dynamic Reducer
const reducer = _dynamicReducer(initialState);
```
✅ **_genericReducer**
A generic reducer accepting predefined handlers for each action type.
```ts
// ⚙️ Generic Reducer with Custom Actions
const reducer = _genericReducer(initialState, customActions);
```
✅ **_importFile**
It supports multiple types of result formats:
base64 → returns file as a base64 string (useful for previews or uploads)
buffer → returns file as an ArrayBuffer (for binary handling)
file → returns the raw File object (for form submission or re-uploads)
unit8array → returns a Uint8Array (for low-level binary use)
```ts
const handleChangeFile = async (file) => {
const result = await _importFile(file, 'base64');
console.log('result', result);
};
```
✅ **_exportExcel**
Exports JSON data to an Excel or CSV file.
```ts
await _exportExcel({
data: [
{ name: 'siya', age: 5 },
{ name: 'riya', age: 6 },
],
filename: 'users',
})
.then(() => console.log('Export successful'))
.catch((err) => console.error('Export failed:', err.message));
```
✅ **_importExcel**
Exports JSON data to an Excel file.
```ts
// 📤 Import to Excel
const fileInputHandler = async (event: React.ChangeEvent<HTMLInputElement>) => {
const { data, error } = await _importExcel(event);
if (error) {
console.error('Error:', error.message);
return;
}
if (data) {
console.log('Successfully parsed data:', data);
}
};
```
✅ **_thousandSeparator**
Formats a number with thousand separators and fixed decimal precision.
```ts
// 💰 Thousand Separator
const formatted = _thousandSeparator(1234567.89);
```
✅ **_getFinancialYear**
Returns the current financial year based on today's date.
```ts
// 📆 Get Financial Year
const fy = _getFinancialYear();
```
✅ **_dateFormat**
Formats a date using Moment.js with the specified format.
```ts
const formatted = _dateFormat(new Date(), 'YYYY-MM-DD');
```
✅ **_dateTransformer**
Recursively formats all dates in an object or array.
```ts
const result = _dateTransformer(data);
```
✅ **_getStorage**
Handles local/session storage actions like GET, SET, REMOVE, CLEAR.
```ts
// 🗃️ Use Local Storage
const data = _getStorage({ action: 'GET', type: 'local', key: 'user' });
```
✅ **_convertToCurrency**
Converts a number to a formatted currency string.
```ts
// 💵 Convert to Currency
const price = _convertToCurrency(2500, 'INR');
```
✅ **_parseJSON**
Safely parses a JSON string into an object.
```ts
// 📦 Parse JSON
const obj = _parseJSON(jsonString);
```
✅ **_stringifyJSON**
Safely converts an object to a JSON string.
```ts
// 🧾 Stringify JSON
const str = _stringifyJSON(obj);
```
✅ **_getCookie**
Retrieves a cookie value by its name.
```ts
// 🍪 Get Cookie
const token = _getCookie('auth_token');
```
✅ **_setCookie**
Sets a cookie with a name, value, and expiry (in days).
```ts
// 📝 Set Cookie
_setCookie('auth_token', 'abc123', 7);
```
✅ **_getBrowserInfo**
Returns the name of the browser (e.g., Chrome, Firefox).
```ts
// 🌐 Get Browser Info
const browser = _getBrowserInfo();
```
✅ **_generatePassword**
Generates a strong random password with mixed characters.
```ts
// 🔑 Generate Random Password
const newPassword = _generatePassword(12);
```
✅ **_getStartStopTime**
Returns the start and end datetime of a given date's month in specified format.
```ts
// 🕐 Get Start & Stop Time
const { startTime, stopTime } = _getStartStopTime(new Date());
```
✅ **getUTCTimestamp**
Returns the UTC timestamp.
```ts
const ts3 = getUTCTimestamp({ year: 2025, month: "December", day: 25, hour: 10, minute: 30 });
console.log(new Date(ts3).toUTCString()); // Thu, 25 Dec 2025 10:30:00 GMT
```
✅ **_setTouchedFields**
Marks all fields with errors as touched in a Formik form.
```ts
_setTouchedFields(formRef, errors);
```
✅ **_isValidForm**
Validates a Formik form and returns whether it's valid.
```ts
const isValid = await _isValidForm(formRef);
```
✅ **_validateFormRef**
Returns form validity and error details from a Formik ref.
```ts
const { isValid, errors } = await _validateFormRef(formRef);
```
✅ **_initializeFormValues**
Initializes form values with empty strings for each field.
```ts
const initialValues = _initializeFormValues(['name', 'email']);
```
✅ **_dynamicRequiredValidation**
Generates a Yup schema with required validations for given fields.
```ts
const schema = _dynamicRequiredValidation(['name', 'email']);
```
✅ **_generateYupValidation**
Creates a Yup validation schema with all fields marked as required.
```ts
const schema = _generateYupValidation(['name', 'age']);
```
✅ **_initializeFormikFields**
Returns an object with default empty string values for Formik fields.
```ts
const formikFields = _initializeFormikFields(['username', 'password']);
```
✅ **_isNotEmpty**
Checks if a given value is not empty — returns false for empty arrays, empty objects, and falsy values like null, undefined, false, or ''.
```ts
const isEmpty = _isNotEmpty([]);
```
✅ **_isEmptyArray**
Checks if a given value is an empty array.
```ts
const isEmpty = _isEmptyArray([]);
```
✅ **_isEmptyObject**
Checks if an object has no own properties.
```ts
const isObjEmpty = _isEmptyObject({});
```
✅ **_isValueInArray**
Checks whether a value exists in a given array.
```ts
// 🔍 Value in Array
const exists = _isValueInArray([1, 2, 3], 2);
```
✅ **_sleep**
Creates a delay for a given time using Promise.
```ts
// ⏳ Delay Execution
await _sleep(1000);
```
✅ **_hasItem**
Searches recursively in a menu tree to find an item by `path`.
```ts
// 🧭 Find Menu Item by Path
const item = _hasItem(menuItems, "/dashboard");
```
✅ **_hasElement**
Searches recursively in a menu tree to find an element by key and value.
```ts
// 🔎 Find Element in Menu
const found = _hasElement(menuItems, "id", 5);
```
✅ **_flattenArray**
Flattens nested arrays by recursively extracting `item.data` if present.
```ts
// 🔁 Flatten Nested Arrays
const flat = _flattenArray(nestedArray);
```
✅ **_filterByMatchedKey**
Filters `list1` based on matching key values from `list2`.
```ts
// 🔍 Filter by matching key in both lists
const filtered = _filterByMatchedKey(usersList, activeUsers, "userId");
```
✅ **_filterByMatchingKey**
Filters `list1` by comparing the key's value in `list2`, with more validation than `_filterByMatchedKey`.
```ts
// 🔍 Filter with validation for objects
const filtered = _filterByMatchingKey(productList, inStockItems, "productId");
```
✅ **_filterArrayByKeyValue**
Filters an array by a key-value match. Defaults to filtering where the key's value is `true`.
```ts
// ✅ Filter by key value
const enabledUsers = _filterArrayByKeyValue(userList, "isActive", true);
```
✅ **_deepClone**
Deep clones an object using `JSON.stringify` and `JSON.parse`.
```ts
// 🧬 Deep Clone
const clone = _deepClone(originalObj);
```
✅ **_mergeObjects**
Merges two objects, giving priority to the second object’s properties.
```ts
// 🔀 Merge Objects
const merged = _mergeObjects(obj1, obj2);
```
✅ **_mapObject**
Maps over an object and returns an array using a callback.
```ts
// 🗺️ Map Object
const result = _mapObject(myObj, (key, value) => `${key}: ${value}`);
```
✅ **_isEqual**
Checks deep equality of two values using `JSON.stringify`.
```ts
// 🟰 Check Equality
const isSame = _isEqual(obj1, obj2);
```
✅ **_capitalize**
Capitalizes the first character of a string.
```ts
// 🔡 Capitalize
const name = _capitalize("john");
```
### ✅ **_countWords**
Counts the number of words in a string by trimming whitespace and splitting by spaces.
```ts
const wordCount = _countWords(' Hello world! How are you? ');
// Output: 5
```
---
✅ **_isMobile**
Detects if the current device is a mobile device.
```ts
// 📱 Check if Mobile
const mobile = _isMobile();
```
---
✅ **_scrollToTop**
Scrolls the page smoothly to the top.
```ts
// ⬆️ Scroll to Top
_scrollToTop();
```
---
✅ **_batchProcess**
Processes an array of data in asynchronous batches.
```ts
await _batchProcess(myArray, 10, async (item) => {
await handleItem(item);
});
```
---
✅ **_flattenObject**
Flattens a nested object into dot notation key-value pairs.
```ts
const flat = _flattenObject({ a: { b: 1 } }); // { 'a.b': 1 }
```
✅ **_deepMerge**
Recursively merges two objects.
```ts
const merged = _deepMerge(obj1, obj2);
```
✅ **_chunk**
Splits an array into chunks of a given size.
```ts
const parts = _chunk([1, 2, 3, 4], 2); // [[1,2], [3,4]]
```
✅ **_asyncDebounce**
Debounces an async function call.
```ts
const debouncedFn = _asyncDebounce(fetchData, 500);
debouncedFn();
```
✅ **_deepCloneArray**
Deeply clones an array of objects.
```ts
const cloned = _deepCloneArray(originalArray);
```
✅ **_getMaxMinValue**
Finds the max and min values in an array.
```ts
const { max, min } = _getMaxMinValue([5, 2, 9]);
```
✅ **_asyncMap**
Async map over array items one by one.
```ts
const results = await _asyncMap(ids, fetchById);
```
✅ **_transformAsyncData**
Applies a transformer to each array item asynchronously.
```ts
const updated = await _transformAsyncData(data, transformFn);
```
✅ **_getNestedProperty**
Retrieves value from object using a string path.
```ts
const value = _getNestedProperty(user, 'profile.name');
```
✅ **_deepEqual**
Deep comparison between two objects.
```ts
const isSame = _deepEqual(objA, objB);
```
✅ **_mergeArrays**
Merges two arrays and removes duplicates.
```ts
const merged = _mergeArrays(arr1, arr2);
```
✅ **_filterDuplicates**
Removes duplicates based on a specific object key.
```ts
const unique = _filterDuplicates(users, 'id');
```
✅ **_sortByKey**
Sorts array of objects by a specific key.
```ts
const sorted = _sortByKey(products, 'price');
```
✅ **_mapAsync**
Parallel async map over array.
```ts
const data = await _mapAsync(users, fetchDetails);
```
✅ **_formatDate**
Formats a date based on a custom pattern.
```ts
_formatDate(new Date(), 'YMD'); // e.g., "Apr 9, 2025"
```
✅ **_calPercentage**
Calculates the percentage of a value relative to total.
```ts
_calPercentage(40, 200); // 20
```
✅ **_sum**
Returns the sum of an array of numbers.
```ts
_sum([1, 2, 3]); // 6
```
✅ **_average**
Calculates the average of numbers in an array.
```ts
_average([4, 8]); // 6
```
✅ **_getPriceAfterTax**
Adds tax to a given price.
```ts
_getPriceAfterTax(100, 18); // 118
```
✅ **_calculateTimeDifference**
Returns difference between two dates in readable format.
```ts
_calculateTimeDifference(start, end); // "1d 2h 3m 4s"
```
✅ **_arrayIncludesObject**
Checks if array contains object (by value).
```ts
_arrayIncludesObject(arr, obj);
```
✅ **_toCamelCase**
Converts kebab-case or snake_case to camelCase.
```ts
_toCamelCase('hello_world'); // helloWorld
```
✅ **_freeze**
Freezes an object to make it immutable.
```ts
const frozen = _freeze(config);
```
✅ **_isFreeze**
Checks if object is frozen.
```ts
_isFreeze(obj); // true/false
```
✅ **_seal**
Seals an object to prevent adding/removing properties.
```ts
_seal(settings);
```
✅ **_isSeal**
Checks if object is sealed.
```ts
_isSeal(obj); // true/false
```
✅ **_arrayToObject**
Converts array of key-value pairs to object.
```ts
_arrayToObject([['a', 1], ['b', 2]]);
```
✅ **_objectToArray**
Converts object to array of key-value pairs.
```ts
_objectToArray({ a: 1 }); // [['a', 1]]
```
✅ **_arrayToObjectByKey**
Converts array of objects to object using a key.
```ts
_arrayToObjectByKey(users, 'id');
```
✅ **_isInArray**
Checks if a value exists in array.
```ts
_isInArray(['a', 'b'], 'b'); // true
```
✅ **_getObjectValues**
Returns object values as an array.
```ts
_getObjectValues({ a: 1, b: 2 }); // [1, 2]
```
✅ **_swapArrayElements**
Swaps two elements in an array.
```ts
_swapArrayElements(arr, 0, 1);
```
✅ **_filterObjectByKey**
Filters object based on allowed keys.
```ts
_filterObjectByKey(user, ['id', 'name']);
```
✅ **_getScrollPosition**
Returns current window scroll position.
```ts
const { scrollX, scrollY } = _getScrollPosition();
```
✅ **_arrayIntersection**
Returns common elements between two arrays.
```ts
_arrayIntersection([1,2,3], [2,3,4]); // [2,3]
```
✅ **_getArrayOfObjectsByProperty**
Returns all objects with a specific property value.
```ts
_getArrayOfObjectsByProperty(data, 'type', 'active');
```
✅ **_setNestedProperty**
Sets a deeply nested property in an object using a string path.
```ts
_setNestedProperty(obj, 'user.address.city', 'Mumbai');
```
✅ **_transformArray**
Applies a transformation function to each item in an array.
```ts
const result = _transformArray(users, user => user.name);
```
✅ **_findObjectById**
Finds an object in an array by its `id`.
```ts
const item = _findObjectById(items, '123');
```
✅ **_getUniqueValues**
Returns an array of unique values.
```ts
const unique = _getUniqueValues([1, 2, 2, 3]);
```
✅ **_mergeArraysByKey**
Merges two arrays of objects based on a common key.
```ts
const merged = _mergeArraysByKey(arr1, arr2, 'id');
```
✅ **_removeDuplicates**
Removes duplicate objects based on a key.
```ts
const cleaned = _removeDuplicates(data, 'email');
```
✅ **_groupBy**
Groups array items by a given key.
```ts
const grouped = _groupBy(users, 'department');
```
✅ **_arrayDiff**
Returns the difference between two arrays.
```ts
const diff = _arrayDiff(['a', 'b'], ['b']);
```
✅ **_deepCompareArrays**
Checks if two arrays are deeply equal.
```ts
const isEqual = _deepCompareArrays(arr1, arr2);
```
✅ **_updateObjectInArray**
Updates a matching object in an array by key-value.
```ts
const updated = _updateObjectInArray(users, 'id', '123', { name: 'New Name' });
```
✅ **_getKeyByValue**
Returns the first key in an object with the matching value.
```ts
const key = _getKeyByValue(obj, 'targetValue');
```
✅ **_getValueByKey**
Returns the value of a key from an object.
```ts
const value = _getValueByKey(obj, 'username');
```
✅ **_getKeysByValue**
Finds all keys in an object with a specific value.
```ts
const keys = _getKeysByValue(obj, 'active');
```
✅ **_escapeRegExpMatch**
Escapes special characters for regex matching.
```ts
const escaped = _escapeRegExpMatch('a+b*c');
```
✅ **_isExactMatch**
Checks if a string contains an exact word match using regex.
```ts
const match = _isExactMatch('The quick brown fox', 'quick');
```
✅ **_bytesToSize**
Converts byte size into a human-readable format.
```ts
const size = _bytesToSize(1024); // "1 KB"
```
✅ **_swapArrayByKey**
Sorts an array in descending order based on a key.
```ts
const sorted = _swapArrayByKey(data, 'score');
```
✅ **_allowDecimalKeys**
Allows only decimal input and valid control keys.
```ts
<input onKeyDown={_allowDecimalKeys} />
```
✅ **_allowAlphaKeys**
Allows only alphabetic input and valid control keys.
```ts
<input onKeyDown={_allowAlphaKeys} />
```
✅ **_handlePasteDecimalKeys**
Prevents pasting invalid decimal values.
```ts
<input onPaste={_handlePasteDecimalKeys} />
```
✅ **_handlePasteAlphabetKeys**
Prevents pasting non-alphabetic characters.
```ts
<input onPaste={_handlePasteAlphabetKeys} />
```
✅ **_allowAlphaNumericKeys**
Allows only alphanumeric keys during typing.
```ts
document.addEventListener('keydown', _allowAlphaNumericKeys);
```
✅ **_domSelector**
Selects a single or all DOM elements matching a CSS selector.
```ts
// 🔍 Select DOM Element
const el = _domSelector('#myElement');
// 🔍 Select All DOM Elements
const elements = _domSelector('.list-item', true);
```
✅ **_hideElement**
Hides a DOM element by setting its `display` style to `'none'`.
```ts
// 🙈 Hide Element
_hideElement('#modal');
```
✅ **_showElement**
Displays a hidden DOM element using the provided `displayType` (default is `'block'`).
```ts
// 👁️ Show Element
_showElement('#modal');
// 👁️ Show with Custom Display Type
_showElement('#modal', 'flex');
```
✅ **_removeElement**
Removes the **first matched** DOM element from the document.
```ts
// ❌ Remove Element
_removeElement('#banner');
```
✅ **_removeNode**
Removes **all matched** DOM elements from the document.
```ts
// 🧹 Remove All Matching Nodes
_removeNode('.temp-item');
```
✅ **_removeSafeElement**
Safely removes an element if it exists and has a parent.
```ts
// 🛡️ Safe Remove Element
_removeSafeElement('#popup');
```
✅ **_clearNode**
Hides specific sibling DOM nodes relative to a base element.
```ts
_clearNode('.my-element', [{ type: 'previous', steps: 1 }]);
```
✅ **_isElementPresent**
Checks if an element exists in the DOM.
```ts
const exists = _isElementPresent('.my-element');
```
✅ **_removeElement**
Removes an element from the DOM.
```ts
_removeElement('#to-remove');
```
✅ **_getParent**
Returns parent of a DOM element.
```ts
const parent = _getParent('.child');
```
✅ **_getChildElements**
Returns child elements of a selector.
```ts
const children = _getChildElements('.container');
```
✅ **_handleParentsMenu**
Recursively updates parent menu's assigned state and permissions based on children.
```ts
_handleParentsMenu(menuList, menuId);
```
✅ **_handleParentNode**
Recursively updates parent permissions based on child permissions.
```ts
_handleParentNode(menuList, menuId, permissionKey);
```
✅ **_handleChildrenMenu**
Recursively sets assigned state and permissions of child nodes.
```ts
_handleChildrenMenu(menuList, parentKey, checked);
```
✅ **_replaceContent**
Replaces inner HTML of an element.
```ts
_replaceContent('#content', '<p>New content</p>');
```
✅ **_cloneElement**
Clones a DOM element.
```ts
const clone = _cloneElement('.to-clone');
```
✅ **_scrollToElement**
Scrolls smoothly to an element.
```ts
_scrollToElement('#target');
```
✅ **_isElementInViewport**
Checks if element is visible in viewport.
```ts
const isVisible = _isElementInViewport('.my-element');
```
✅ **_setElementDisabled**
Enables or disables a DOM element.
```ts
_setElementDisabled('#submit-btn', true);
```
✅ **_addEventListenerToElement**
Attaches an event listener to a DOM element.
```ts
_addEventListenerToElement('#my-btn', 'click', handleClick);
```
✅ **_removeEventListenerFromElement**
Removes a specific event listener.
```ts
_removeEventListenerFromElement('#my-btn', 'click', handleClick);
```
✅ **_getElementAttribute**
Gets the value of an element’s attribute.
```ts
const id = _getElementAttribute('.item', 'data-id');
```
✅ **_setElementAttribute**
Sets an attribute on a DOM element.
```ts
_setElementAttribute('.item', 'data-id', '123');
```
✅ **_removeElementAttribute**
Removes an attribute from an element.
```ts
_removeElementAttribute('.item', 'data-id');
```
✅ **_removeAllChildren**
Clears all child nodes of an element.
```ts
_removeAllChildren('#container');
```
✅ **_getElementsByClass**
Returns elements with a given class.
```ts
const elements = _getElementsByClass('my-class');
```
✅ **_getElementsByTag**
Returns elements with a given tag name.
```ts
const buttons = _getElementsByTag('button');
```
✅ **_setMultipleStyles**
Applies multiple CSS styles to an element.
```ts
_setMultipleStyles('.card', { color: 'red', fontWeight: 'bold' });
```
✅ **_insertHTML**
Injects HTML at a specific position.
```ts
_insertHTML('#box', 'beforeend', '<div>Hello</div>');
```
✅ **_isDocumentLoaded**
Checks if the document has fully loaded.
```ts
if (_isDocumentLoaded()) { /* safe to run code */ }
```
✅ **_runOnIframeLoad**
Runs a callback when iframe finishes loading.
```ts
_runOnIframeLoad('#myIframe', () => console.log('Loaded'));
```
✅ **_reloadAfterLoad**
Reloads page after a delay post-load.
```ts
_reloadAfterLoad(3000); // Reload 3s after load
```
✅ **_isValidEmail**
Checks if a string is a valid email address.
```ts
// 📧 Validate Email
const isValid = _isValidEmail('user@example.com');
```
✅ **_isValidPhoneNumber**
Checks if a string is a valid international phone number (10–15 digits).
```ts
// 📱 Validate Phone Number
const isValid = _isValidPhoneNumber('+919876543210');
```
✅ **_isValidURL**
Checks if a string is a valid URL format.
```ts
// 🌐 Validate URL
const isValid = _isValidURL('https://example.com');
```
✅ **_isValidDate**
Checks if a string matches the `YYYY-MM-DD` date format.
```ts
// 📅 Validate Date
const isValid = _isValidDate('2025-04-09');
```
✅ **_isValidTime**
Checks if a string is a valid 24-hour `HH:mm` format.
```ts
// ⏰ Validate Time
const isValid = _isValidTime('23:59');
```
✅ **_isValidDateTime**
Checks if a string matches the `YYYY-MM-DDTHH:mm:ss` format.
```ts
// 🕒 Validate DateTime
const isValid = _isValidDateTime('2025-04-09T12:30:00');
```
✅ **_isValidDateRange**
Checks if the start date is earlier than or equal to the end date.
```ts
// 🔄 Validate Date Range
const isValid = _isValidDateRange('2025-01-01', '2025-12-31');
```
✅ **_isValidPassword**
Checks if a password has 8+ characters, at least 1 letter and 1 number.
```ts
// 🔐 Validate Password
const isValid = _isValidPassword('Abc12345');
```
✅ **_isValidUsername**
Checks if a username is 3+ characters and contains only letters, numbers, dots, underscores, or hyphens.
```ts
// 👤 Validate Username
const isValid = _isValidUsername('john_doe');
```
✅ **_isValidCreditCard**
Checks if a string matches known credit card patterns.
```ts
// 💳 Validate Credit Card
const isValid = _isValidCreditCard('4111111111111111');
```
✅ **_isValidHexColor**
Checks if a string is a valid hex color code.
```ts
// 🎨 Validate Hex Color
const isValid = _isValidHexColor('#FF5733');
```
✅ **_isValidIP**
Checks if a string is a valid IPv4 address.
```ts
// 🌐 Validate IP Address
const isValid = _isValidIP('192.168.1.1');
```
✅ **_isValidMacAddress**
Checks if a string is a valid MAC address.
```ts
// 💻 Validate MAC Address
const isValid = _isValidMacAddress('00:1A:2B:3C:4D:5E');
```
✅ **_isValidUUID**
Checks if a string is a valid UUID (v1 to v5).
```ts
// 🆔 Validate UUID
const isValid = _isValidUUID('550e8400-e29b-41d4-a716-446655440000');
```
✅ **_isValidBase64**
Checks if a string is a valid Base64-encoded value.
```ts
// 🧬 Validate Base64
const isValid = _isValidBase64('U29tZSB0ZXh0');
```
✅ **_isValidJSON**
Checks if a string is valid JSON.
```ts
// 📦 Validate JSON
const isValid = _isValidJSON('{"name":"John"}');
```
✅ **_isValidFunction**
Checks if the input is a valid function.
```ts
// 🛠️ Validate Function
const isValid = _isValidFunction(() => {});
```
✅ **_isValidString**
Checks if the input is a non-empty string.
```ts
// ✏️ Validate String
const isValid = _isValidString('Hello');
```
✅ **_isValidNumber**
Checks if the input is a valid number.
```ts
// 🔢 Validate Number
const isValid = _isValidNumber(123.45);
```
✅ **_isValidBoolean**
Checks if the input is a boolean.
```ts
// ✅ Validate Boolean
const isValid = _isValidBoolean(true);
```
✅ **_isValidDateObject**
Checks if the input is a valid `Date` object.
```ts
// 📆 Validate Date Object
const isValid = _isValidDateObject(new Date());
```
✅ **_isValidBlob**
Checks if the input is a `Blob`.
```ts
// 🗂️ Validate Blob
const isValid = _isValidBlob(new Blob(['text']));
```
✅ **_isLeapYear**
Determines whether a given year is a leap year based on calendar rules.
```ts
const isLeap = _isLeapYear(2024);
// Output: true
```
✅ **_isWeekend**
Checks if a given date falls on a weekend (Saturday or Sunday).
```ts
const weekend = _isWeekend(new Date('2025-06-08'));
// Output: true // (Sunday)
```
✅ **_removeFalsy**
Removes all falsy values (`false`, `0`, `''`, `null`, `undefined`, `NaN`) from an array.
```ts
const cleaned = _removeFalsy([0, 1, false, 2, '', 3]);
// Output: [1, 2, 3]
```
✅ **_escapeHTML**
Escapes special HTML characters to prevent injection or rendering issues.
```ts
const safeHTML = _escapeHTML('<div class="test">Tom & Jerry</div>');
// Output: '<div class="test">Tom & Jerry</div>'
```
✅ **_isValidFile**
Checks if the input is a `File`.
```ts
// 📁 Validate File
const isValid = _isValidFile(new File([''], 'file.txt'));
```
✅ **_isValidRegExp**
Checks if the input is a regular expression.
```ts
// 🔍 Validate RegExp
const isValid = _isValidRegExp(/abc/);
```
✅ **_isValidPromise**
Checks if the input is a `Promise`.
```ts
// ⏳ Validate Promise
const isValid = _isValidPromise(Promise.resolve());
```
✅ **_isValidDateString**
Checks if the string can be parsed as a valid date.
```ts
// 🗓️ Validate Date String
const isValid = _isValidDateString('2025-04-09');
```
✅ **_isValidHTMLElement**
Checks if the input is an instance of `HTMLElement`.
```ts
// 🧱 Validate HTMLElement
const isValid = _isValidHTMLElement(document.body);
```
✅ **_isValidEvent**
Checks if the input is an instance of `Event`.
```ts
// 🎫 Validate Event
const isValid = _isValidEvent(new Event('click'));
```
✅ **_isValidNode**
Checks if the input is a `Node`.
```ts
// 🌿 Validate Node
const isValid = _isValidNode(document.createTextNode('text'));
```
✅ **_isValidNodeList**
Checks if the input is a `NodeList`.
```ts
// 📚 Validate NodeList
const isValid = _isValidNodeList(document.querySelectorAll('div'));
```
✅ **_isValidHTMLCollection**
Checks if the input is an `HTMLCollection`.
```ts
// 🏗️ Validate HTMLCollection
const isValid = _isValidHTMLCollection(document.forms);
```
✅ **_isValidFormData**
Checks if the input is a `FormData` instance.
```ts
// 📝 Validate FormData
const isValid = _isValidFormData(new FormData());
```
✅ **_isValidURLSearchParams**
Checks if the input is a `URLSearchParams` instance.
```ts
// 🔍 Validate URLSearchParams
const isValid = _isValidURLSearchParams(new URLSearchParams());
```
###
**Approved by** : [**NPM Community**](https://docs.npmjs.com/policies/open-source-terms)
**License** : [**MIT**](https://docs.npmjs.com/policies/npm-license) © 2022–2024