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,474 lines (1,220 loc) • 38.2 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 ✔ |
### **Documentation Site in Progress...**
*We're building an enhanced documentation experience with better navigation and examples. Coming soon!*
## Array Functions
### ✅ **_arrayDiff**
Returns the difference between two arrays.
```ts
const diff = _arrayDiff(['a', 'b'], ['b']); // ['a']
```
### ✅ **_arrayIncludesObject**
Checks if array contains object (by value).
```ts
_arrayIncludesObject(arr, obj);
```
### ✅ **_arrayIntersection**
Returns common elements between two arrays.
```ts
_arrayIntersection([1,2,3], [2,3,4]); // [2,3]
```
### ✅ **_arrayToObject**
Converts array of key-value pairs to object.
```ts
_arrayToObject([['a', 1], ['b', 2]]); // { a: 1, b: 2 }
```
### ✅ **_arrayToObjectByKey**
Converts array of objects to object using a key.
```ts
_arrayToObjectByKey(users, 'id');
```
### ✅ **_asyncMap**
Async map over array items one by one.
```ts
const results = await _asyncMap(ids, fetchById);
```
### ✅ **_average**
Calculates the average of numbers in an array.
```ts
_average([4, 8]); // 6
```
### ✅ **_batchProcess**
Processes an array of data in asynchronous batches.
```ts
await _batchProcess(myArray, 10, async (item) => {
await handleItem(item);
});
```
### ✅ **_chunk**
Splits an array into chunks of a given size.
```ts
const parts = _chunk([1, 2, 3, 4], 2); // [[1,2], [3,4]]
```
### ✅ **_deepCloneArray**
Deeply clones an array of objects.
```ts
const cloned = _deepCloneArray(originalArray);
```
### ✅ **_deepCompareArrays**
Checks if two arrays are deeply equal.
```ts
const isEqual = _deepCompareArrays(arr1, arr2);
```
### ✅ **_extractKeyValues**
Extracts all non-undefined values for a specific key from an array.
```ts
const employees = [
{ id: 1, name: "Alice" },
{ id: 2 },
{ id: 3, name: "Bob" },
];
_extractKeyValues(employees, "name"); // ["Alice", "Bob"]
```
### ✅ **_extractNestedKeyValues**
Extracts all non-undefined values from a nested key path in an array of objects.
```ts
const users = [
{ id: 1, address: { city: "Mumbai" } },
{ id: 2, address: { city: "Pune" } },
{ id: 3 },
];
_extractNestedKeyValues(users, "address.city"); // ["Mumbai", "Pune"]
```
### ✅ **_extractUniqueValues**
Extracts unique values from an array based on a specific key.
```ts
const employees = [
{ id: 1, department: "HR" },
{ id: 2, department: "IT" },
{ id: 3, department: "HR" },
];
_extractUniqueValues(employees, "department"); // ["HR", "IT"]
```
### ✅ **_filterArrayByKeyValue**
Filters an array by a key-value match. Defaults to filtering where the key's value is `true`.
```ts
const enabledUsers = _filterArrayByKeyValue(userList, "isActive", true);
```
### ✅ **_filterByMatchedKey**
Filters `list1` based on matching key values from `list2`.
```ts
const filtered = _filterByMatchedKey(usersList, activeUsers, "userId");
```
### ✅ **_filterByMatchingKey**
Filters `list1` by comparing the key's value in `list2`, with more validation than `_filterByMatchedKey`.
```ts
const filtered = _filterByMatchingKey(productList, inStockItems, "productId");
```
### ✅ **_filterDuplicates**
Removes duplicates based on a specific object key.
```ts
const unique = _filterDuplicates(users, 'id');
```
### ✅ **_findObjectById**
Finds an object in an array by its `id`.
```ts
const item = _findObjectById(items, '123');
```
### ✅ **_flattenArray**
Flattens nested arrays by recursively extracting `item.data` if present.
```ts
const flat = _flattenArray(nestedArray);
```
### ✅ **_flattenArrayByKey**
Flattens an array of objects by extracting and combining values from a specified key.
```ts
_flattenArrayByKey([{ id: 1, items: ['a', 'b'] }, { id: 2, items: ['c'] }], 'items');
// ['a', 'b', 'c']
```
### ✅ **_getArrayOfObjectsByProperty**
Returns all objects with a specific property value.
```ts
_getArrayOfObjectsByProperty(data, 'type', 'active');
```
### ✅ **_getMaxMinValue**
Finds the max and min values in an array.
```ts
const { max, min } = _getMaxMinValue([5, 2, 9]);
```
### ✅ **_getUniqueValues**
Returns an array of unique values.
```ts
const unique = _getUniqueValues([1, 2, 2, 3]);
```
### ✅ **_groupBy**
Groups array items by a given key.
```ts
const grouped = _groupBy(users, 'department');
```
### ✅ **_hasElement**
Searches recursively in a menu tree to find an element by key and value.
```ts
const found = _hasElement(menuItems, "id", 5);
```
### ✅ **_hasItem**
Searches recursively in a menu tree to find an item by `path`.
```ts
const item = _hasItem(menuItems, "/dashboard");
```
### ✅ **_isEmptyArray**
Checks if a given value is an empty array.
```ts
const isEmpty = _isEmptyArray([]);
```
### ✅ **_isInArray**
Checks if a value exists in array.
```ts
_isInArray(['a', 'b'], 'b'); // true
```
### ✅ **_isValueInArray**
Checks whether a value exists in a given array.
```ts
const exists = _isValueInArray([1, 2, 3], 2);
```
### ✅ **_mapAsync**
Parallel async map over array.
```ts
const data = await _mapAsync(users, fetchDetails);
```
### ✅ **_mergeArrays**
Merges two arrays and removes duplicates.
```ts
const merged = _mergeArrays(arr1, arr2);
```
### ✅ **_mergeArraysByKey**
Merges two arrays of objects based on a common key.
```ts
const merged = _mergeArraysByKey(arr1, arr2, 'id');
```
### ✅ **_removeFalsy**
Removes all falsy values (`false`, `0`, `''`, `null`, `undefined`, `NaN`) from an array.
```ts
const cleaned = _removeFalsy([0, 1, false, 2, '', 3]); // [1, 2, 3]
```
### ✅ **_removeDuplicateByKey**
Removes duplicates based on a specific key (e.g. `id`), keeping the **first occurrence**.
```ts
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 1, name: 'Alice Duplicate' },
];
const uniqueUsers = _removeDuplicateByKey(users, 'id');
// Result: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
```
### ✅ **_removeDuplicates**
Removes duplicate objects based on a key.
```ts
const cleaned = _removeDuplicates(data, 'email');
```
### ✅ **_sortByKey**
Sorts array of objects by a specific key.
```ts
const sorted = _sortByKey(products, 'price');
```
### ✅ **_sum**
Returns the sum of an array of numbers.
```ts
_sum([1, 2, 3]); // 6
```
### ✅ **_swapArrayByKey**
Sorts an array in descending order based on a key.
```ts
const sorted = _swapArrayByKey(data, 'score');
```
### ✅ **_swapArrayElements**
Swaps two elements in an array.
```ts
_swapArrayElements(arr, 0, 1);
```
### ✅ **_transformArray**
Applies a transformation function to each item in an array.
```ts
const result = _transformArray(users, user => user.name);
```
### ✅ **_transformAsyncData**
Applies a transformer to each array item asynchronously.
```ts
const updated = await _transformAsyncData(data, transformFn);
```
### ✅ **_updateObjectInArray**
Updates a matching object in an array by key-value.
```ts
const updated = _updateObjectInArray(users, 'id', '123', { name: 'New Name' });
```
---
## Object Functions
### ✅ **_deepClone**
Deep clones an object using `JSON.stringify` and `JSON.parse`.
```ts
const clone = _deepClone(originalObj);
```
### ✅ **_deepEqual**
Deep comparison between two objects.
```ts
const isSame = _deepEqual(objA, objB);
```
### ✅ **_deepMerge**
Recursively merges two objects.
```ts
const merged = _deepMerge(obj1, obj2);
```
### ✅ **_filterObjectByKey**
Filters object based on allowed keys.
```ts
_filterObjectByKey(user, ['id', 'name']);
```
### ✅ **_flattenObject**
Flattens a nested object into dot notation key-value pairs.
```ts
const flat = _flattenObject({ a: { b: 1 } }); // { 'a.b': 1 }
```
### ✅ **_freeze**
Freezes an object to make it immutable.
```ts
const frozen = _freeze(config);
```
### ✅ **_getKeyByValue**
Returns the first key in an object with the matching value.
```ts
const key = _getKeyByValue(obj, 'targetValue');
```
### ✅ **_getKeysByValue**
Finds all keys in an object with a specific value.
```ts
const keys = _getKeysByValue(obj, 'active');
```
### ✅ **_getNestedProperty**
Retrieves value from object using a string path.
```ts
const value = _getNestedProperty(user, 'profile.name');
```
### ✅ **_getObjectValues**
Returns object values as an array.
```ts
_getObjectValues({ a: 1, b: 2 }); // [1, 2]
```
### ✅ **_getValueByKey**
Returns the value of a key from an object.
```ts
const value = _getValueByKey(obj, 'username');
```
### ✅ **_isEmptyObject**
Checks if an object has no own properties.
```ts
const isObjEmpty = _isEmptyObject({});
```
### ✅ **_isEqual**
Checks deep equality of two values using `JSON.stringify`.
```ts
const isSame = _isEqual(obj1, obj2);
```
### ✅ **_isFreeze**
Checks if object is frozen.
```ts
_isFreeze(obj); // true/false
```
### ✅ **_isSeal**
Checks if object is sealed.
```ts
_isSeal(obj); // true/false
```
### ✅ **_mapObject**
Maps over an object and returns an array using a callback.
```ts
const result = _mapObject(myObj, (key, value) => `${key}: ${value}`);
```
### ✅ **_mergeObjects**
Merges two objects, giving priority to the second object's properties.
```ts
const merged = _mergeObjects(obj1, obj2);
```
### ✅ **_objectToArray**
Converts object to array of key-value pairs.
```ts
_objectToArray({ a: 1 }); // [['a', 1]]
```
### ✅ **_seal**
Seals an object to prevent adding/removing properties.
```ts
_seal(settings);
```
### ✅ **_setNestedProperty**
Sets a deeply nested property in an object using a string path.
```ts
_setNestedProperty(obj, 'user.address.city', 'Mumbai');
```
---
## Form & Validation Functions
### ✅ **_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']);
```
### ✅ **_initializeFormValues**
Initializes form values with empty strings for each field.
```ts
const initialValues = _initializeFormValues(['name', 'email']);
```
### ✅ **_isValidForm**
Validates a Formik form and returns whether it's valid.
```ts
const isValid = await _isValidForm(formRef);
```
### ✅ **_setTouchedFields**
Marks all fields with errors as touched in a Formik form.
```ts
_setTouchedFields(formRef, errors);
```
### ✅ **_validateFormRef**
Returns form validity and error details from a Formik ref.
```ts
const { isValid, errors } = await _validateFormRef(formRef);
```
---
## ✅ Validation Functions
### ✅ **_isValidBase64**
Checks if a string is a valid Base64-encoded value.
```ts
const isValid = _isValidBase64('U29tZSB0ZXh0');
```
### ✅ **_isValidBlob**
Checks if the input is a `Blob`.
```ts
const isValid = _isValidBlob(new Blob(['text']));
```
### ✅ **_isValidBoolean**
Checks if the input is a boolean.
```ts
const isValid = _isValidBoolean(true);
```
### ✅ **_isValidCreditCard**
Checks if a string matches known credit card patterns.
```ts
const isValid = _isValidCreditCard('4111111111111111');
```
### ✅ **_isValidDate**
Checks if a string matches the `YYYY-MM-DD` date format.
```ts
const isValid = _isValidDate('2025-04-09');
```
### ✅ **_isValidDateObject**
Checks if the input is a valid `Date` object.
```ts
const isValid = _isValidDateObject(new Date());
```
### ✅ **_isValidDateRange**
Checks if the start date is earlier than or equal to the end date.
```ts
const isValid = _isValidDateRange('2025-01-01', '2025-12-31');
```
### ✅ **_isValidDateTime**
Checks if a string matches the `YYYY-MM-DDTHH:mm:ss` format.
```ts
const isValid = _isValidDateTime('2025-04-09T12:30:00');
```
### ✅ **_isValidDateString**
Checks if the string can be parsed as a valid date.
```ts
const isValid = _isValidDateString('2025-04-09');
```
### ✅ **_isValidEmail**
Checks if a string is a valid email address.
```ts
const isValid = _isValidEmail('user@example.com');
```
### ✅ **_isValidEvent**
Checks if the input is an instance of `Event`.
```ts
const isValid = _isValidEvent(new Event('click'));
```
### ✅ **_isValidFile**
Checks if the input is a `File`.
```ts
const isValid = _isValidFile(new File([''], 'file.txt'));
```
### ✅ **_isValidFormData**
Checks if the input is a `FormData` instance.
```ts
const isValid = _isValidFormData(new FormData());
```
### ✅ **_isValidFunction**
Checks if the input is a valid function.
```ts
const isValid = _isValidFunction(() => {});
```
### ✅ **_isValidHexColor**
Checks if a string is a valid hex color code.
```ts
const isValid = _isValidHexColor('#FF5733');
```
### ✅ **_isValidHTMLCollection**
Checks if the input is an `HTMLCollection`.
```ts
const isValid = _isValidHTMLCollection(document.forms);
```
### ✅ **_isValidHTMLElement**
Checks if the input is an instance of `HTMLElement`.
```ts
const isValid = _isValidHTMLElement(document.body);
```
### ✅ **_isValidIP**
Checks if a string is a valid IPv4 address.
```ts
const isValid = _isValidIP('192.168.1.1');
```
### ✅ **_isValidJSON**
Checks if a string is valid JSON.
```ts
const isValid = _isValidJSON('{"name":"John"}');
```
### ✅ **_isValidMacAddress**
Checks if a string is a valid MAC address.
```ts
const isValid = _isValidMacAddress('00:1A:2B:3C:4D:5E');
```
### ✅ **_isValidNode**
Checks if the input is a `Node`.
```ts
const isValid = _isValidNode(document.createTextNode('text'));
```
### ✅ **_isValidNodeList**
Checks if the input is a `NodeList`.
```ts
const isValid = _isValidNodeList(document.querySelectorAll('div'));
```
### ✅ **_isValidNumber**
Checks if the input is a valid number.
```ts
const isValid = _isValidNumber(123.45);
```
### ✅ **_isValidPassword**
Checks if a password has 8+ characters, at least 1 letter and 1 number.
```ts
const isValid = _isValidPassword('Abc12345');
```
### ✅ **_isValidPhoneNumber**
Checks if a string is a valid international phone number (10–15 digits).
```ts
const isValid = _isValidPhoneNumber('+919876543210');
```
### ✅ **_isValidPromise**
Checks if the input is a `Promise`.
```ts
const isValid = _isValidPromise(Promise.resolve());
```
### ✅ **_isValidRegExp**
Checks if the input is a regular expression.
```ts
const isValid = _isValidRegExp(/abc/);
```
### ✅ **_isValidString**
Checks if the input is a non-empty string.
```ts
const isValid = _isValidString('Hello');
```
### ✅ **_isValidTime**
Checks if a string is a valid 24-hour `HH:mm` format.
```ts
const isValid = _isValidTime('23:59');
```
### ✅ **_isValidURL**
Checks if a string is a valid URL format.
```ts
const isValid = _isValidURL('https://example.com');
```
### ✅ **_isValidURLSearchParams**
Checks if the input is a `URLSearchParams` instance.
```ts
const isValid = _isValidURLSearchParams(new URLSearchParams());
```
### ✅ **_isValidUsername**
Checks if a username is 3+ characters and contains only letters, numbers, dots, underscores, or hyphens.
```ts
const isValid = _isValidUsername('john_doe');
```
### ✅ **_isValidUUID**
Checks if a string is a valid UUID (v1 to v5).
```ts
const isValid = _isValidUUID('550e8400-e29b-41d4-a716-446655440000');
```
### ✅ **_isTruncate**
Checks if text would be truncated based on the character limit.
```ts
_isTruncate('This is a long text example', 10);
// Returns: true
```
## Security & Encryption Functions
### ✅ **_decryptJson**
Decrypts AES-encrypted JSON string using a secret key.
```ts
const decrypted = _decryptJson(encryptedString, "secret123");
```
### ✅ **_decryptString**
Decrypts an AES-encrypted string using the provided IV and secret key.
```ts
const plainText = _decryptString(ciphertext, iv, "secretKey");
```
### ✅ **_encryptJson**
Encrypts a JSON object using AES encryption with a secret key.
```ts
const encrypted = _encryptJson({ name: "John" }, "secret123");
```
### ✅ **_encryptPayload**
Encrypts a full payload using a randomly generated key and IV, secured by a static key.
```ts
const payload = _encryptPayload({ id: 1 }, "mainSecretKey");
```
### ✅ **_encryptString**
Encrypts a plain string using AES encryption, with optional random IV.
```ts
const result = _encryptString("mySecretText", "secretKey");
```
### ✅ **_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>'
```
### ✅ **_generatePassword**
Generates a strong random password with mixed characters.
```ts
const newPassword = _generatePassword(12);
```
---
## Event & DOM Functions
### ✅ **_addEventListenerToElement**
Attaches an event listener to a DOM element.
```ts
_addEventListenerToElement('#my-btn', 'click', handleClick);
```
### ✅ **_allowAlphaKeys**
Allows only alphabetic input and valid control keys.
```ts
<input onKeyDown={_allowAlphaKeys} />
```
### ✅ **_allowAlphaNumericKeys**
Allows only alphanumeric keys during typing.
```ts
document.addEventListener('keydown', _allowAlphaNumericKeys);
```
### ✅ **_allowDecimalKeys**
Allows only decimal input and valid control keys.
```ts
<input onKeyDown={_allowDecimalKeys} />
```
### ✅ **_clearNode**
Hides specific sibling DOM nodes relative to a base element.
```ts
_clearNode('.my-element', [{ type: 'previous', steps: 1 }]);
```
### ✅ **_cloneElement**
Clones a DOM element.
```ts
const clone = _cloneElement('.to-clone');
```
### ✅ **_domSelector**
Selects a single or all DOM elements matching a CSS selector.
```ts
const el = _domSelector('#myElement');
const elements = _domSelector('.list-item', true);
```
### ✅ **_getChildElements**
Returns child elements of a selector.
```ts
const children = _getChildElements('.container');
```
### ✅ **_getElementAttribute**
Gets the value of an element's attribute.
```ts
const id = _getElementAttribute('.item', 'data-id');
```
### ✅ **_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');
```
### ✅ **_getParent**
Returns parent of a DOM element.
```ts
const parent = _getParent('.child');
```
### ✅ **_getScrollPosition**
Returns current window scroll position.
```ts
const { scrollX, scrollY } = _getScrollPosition();
```
### ✅ **_handlePasteAlphabetKeys**
Prevents pasting non-alphabetic characters.
```ts
<input onPaste={_handlePasteAlphabetKeys} />
```
### ✅ **_handlePasteDecimalKeys**
Prevents pasting invalid decimal values.
```ts
<input onPaste={_handlePasteDecimalKeys} />
```
### ✅ **_hideElement**
Hides a DOM element by setting its `display` style to `'none'`.
```ts
_hideElement('#modal');
```
### ✅ **_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 */ }
```
### ✅ **_isElementInViewport**
Checks if element is visible in viewport.
```ts
const isVisible = _isElementInViewport('.my-element');
```
### ✅ **_isElementPresent**
Checks if an element exists in the DOM.
```ts
const exists = _isElementPresent('.my-element');
```
### ✅ **_onDOMLoad**
Executes the callback when the **DOM is fully parsed**, but before images and other resources are necessarily loaded.
```ts
_onDOMLoad(() => {
const el = document.getElementById('app');
console.log('DOM ready:', el);
});
```
### ✅ **_onFullReload**
Executes the callback **only when the page is reloaded** (not on SPA route changes or soft navigation).
```ts
_onFullReload(() => {
console.log('Page was fully reloaded.');
});
```
### ✅ **_onWindowLoad**
Executes the callback when the **entire window is fully loaded**, including all images and assets.
```ts
_onWindowLoad(() => {
console.log('Window fully loaded!');
});
```
### ✅ **_reloadAfterLoad**
Reloads page after a delay post-load.
```ts
_reloadAfterLoad(3000); // Reload 3s after load
```
### ✅ **_removeAllChildren**
Clears all child nodes of an element.
```ts
_removeAllChildren('#container');
```
### ✅ **_removeElement**
Removes the **first matched** DOM element from the document.
```ts
_removeElement('#banner');
```
### ✅ **_removeElementAttribute**
Removes an attribute from an element.
```ts
_removeElementAttribute('.item', 'data-id');
```
### ✅ **_removeEventListenerFromElement**
Removes a specific event listener.
```ts
_removeEventListenerFromElement('#my-btn', 'click', handleClick);
```
### ✅ **_removeNode**
Removes **all matched** DOM elements from the document.
```ts
_removeNode('.temp-item');
```
### ✅ **_removeSafeElement**
Safely removes an element if it exists and has a parent.
```ts
_removeSafeElement('#popup');
```
### ✅ **_replaceContent**
Replaces inner HTML of an element.
```ts
_replaceContent('#content', '<p>New content</p>');
```
### ✅ **_runOnIframeLoad**
Runs a callback when iframe finishes loading.
```ts
_runOnIframeLoad('#myIframe', () => console.log('Loaded'));
```
### ✅ **_scrollToElement**
Scrolls smoothly to an element.
```ts
_scrollToElement('#target');
```
### ✅ **_scrollToTop**
Scrolls the page smoothly to the top.
```ts
_scrollToTop();
```
### ✅ **_setElementAttribute**
Sets an attribute on a DOM element.
```ts
_setElementAttribute('.item', 'data-id', '123');
```
### ✅ **_setElementDisabled**
Enables or disables a DOM element.
```ts
_setElementDisabled('#submit-btn', true);
```
### ✅ **_setMultipleStyles**
Applies multiple CSS styles to an element.
```ts
_setMultipleStyles('.card', { color: 'red', fontWeight: 'bold' });
```
### ✅ **_showElement**
Displays a hidden DOM element using the provided `displayType` (default is `'block'`).
```ts
_showElement('#modal');
_showElement('#modal', 'flex');
```
---
## File & Data Functions
### ✅ **_base64ToBlob**
Converts a base64-encoded string into a Blob object.
```ts
const blob = _base64ToBlob(base64String);
```
### ✅ **_downloadBase64File**
Downloads any base64-encoded data as a file with a specified filename and extension.
```ts
const base64Image = 'iVBORw0KGgoAAAANSUhEUgAAA...';
downloadBase64File(base64Image, 'my-picture.png');
const base64PDF = 'JVBERi0xLjQKJeLjz9MNCjEgMCBvYmoK...';
downloadBase64File(base64PDF, 'invoice.pdf');
```
### ✅ **_downloadBlob**
Triggers download of a Blob object.
```ts
_downloadBlob(blob, 'myfile.pdf');
```
### ✅ **_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));
```
### ✅ **_fileToBase64**
Converts a file to a base64-encoded string.
```ts
const base64 = await _fileToBase64(file);
```
### ✅ **_importExcel**
Imports data from an Excel file.
```ts
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);
}
};
```
### ✅ **_importFile**
Supports multiple types of result formats: base64, buffer, file, unit8array.
```ts
const handleChangeFile = async (file) => {
const result = await _importFile(file, 'base64');
console.log('result', result);
};
```
---
## Browser & Storage Functions
### ✅ **_navigate**
Navigates to a new path with optional state and replace behavior.
```ts
_navigate('/about', { state: { user: 'sia' }, replace: true });
```
### ✅ **_go**
Navigates through the history stack by a specified number of steps.
```ts
_go(-2); // Go back 2 pages
_go(1); // Go forward 1 page
```
### ✅ **_goBack**
Navigates to the previous page in history.
```ts
_goBack(); // Equivalent to browser back button
```
### ✅ **_goForward**
Navigates to the next page in history.
```ts
_goForward(); // Equivalent to browser forward button
```
### ✅ **_getCurrentPath**
Returns the current pathname from the navigation state.
```ts
_getCurrentPath(); // e.g., "/about"
```
### ✅ **_getCurrentState**
Returns the current navigation state object.
```ts
_getCurrentState(); // e.g., { user: 'sia' }
```
### ✅ **_getLocation**
Returns both the current path and state as an object.
```ts
_getLocation(); // e.g., { pathname: "/about", state: { user: 'sia' } }
```
### ✅ **_getTypedState**
Returns the current navigation state with TypeScript type safety.
```ts
interface UserState { name: string; age: number; }
_getTypedState<UserState>(); // Returns typed state or null
```
### ✅ **_clearRouteState**
Removes the route state from the browser's history without reloading the page, keeping the current path intact.
```ts
_clearRouteState('/dashboard');
```
### ✅ **_findExactRoute**
Finds an exact route match from an array of routes based on a pathname.
```ts
_findExactRoute([{ path: '/users' }, { path: '/users/:id' }], '/users/123');
// { path: '/users/:id' }
```
### ✅ **_copyText**
Copies the provided text to the clipboard, using modern APIs with a fallback for older browsers.
```ts
const success = await _copyText("Hello, clipboard!");
if (success) {
console.log("Text copied successfully");
}
```
### ✅ **_getBrowserInfo**
Returns the name of the browser (e.g., Chrome, Firefox).
```ts
const browser = _getBrowserInfo();
```
### ✅ **_getCookie**
Retrieves a cookie value by its name.
```ts
const token = _getCookie('auth_token');
```
### ✅ **_getQueryString**
Returns the query string from the current URL, supporting both `?search` and `#hash?search` formats.
```ts
const query = _getQueryString();
console.log('Query string:', query); // Example: ?id=123
```
### ✅ **_getStorage**
Handles local/session storage actions like GET, SET, REMOVE, CLEAR.
```ts
const data = _getStorage({ action: 'GET', type: 'local', key: 'user' });
```
### ✅ **_isMobile**
Detects if the current device is a mobile device.
```ts
const mobile = _isMobile();
```
### ✅ **_pasteText**
Retrieves and returns the current text content from the clipboard, using modern APIs with a fallback for older browsers.
```ts
const text = await _pasteText();
if (text) {
console.log("Pasted text:", text);
}
```
### ✅ **_setCookie**
Sets a cookie with a name, value, and expiry (in days).
```ts
_setCookie('auth_token', 'abc123', 7);
```
---
## String & Text Functions
### ✅ **_bytesToSize**
Converts byte size into a human-readable format.
```ts
const size = _bytesToSize(1024); // "1 KB"
```
### ✅ **_capitalize**
Capitalizes the first character of a string.
```ts
const name = _capitalize("john"); // "John"
```
### ✅ **_truncateText**
Truncates text to a specified character limit and adds ellipsis if truncated.
```ts
_truncateText('This is a long text example', 10);
// Returns: "This is a…"
```
### ✅ **_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? '); // 5
```
### ✅ **_decodeURI**
Decodes an encoded URI component back to its original readable string format.
```ts
const decoded = _decodeURI('hello%20world%402024'); // 'hello world@2024'
```
### ✅ **_encodeURI**
Encodes a URI component by escaping special characters to make it safe for use in URLs.
```ts
const encoded = _encodeURI('hello world@2024'); // 'hello%20world%402024'
```
### ✅ **_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');
```
### ✅ **_parseJSON**
Safely parses a JSON string into an object.
```ts
const obj = _parseJSON(jsonString);
```
### ✅ **_stringifyJSON**
Safely converts an object to a JSON string.
```ts
const str = _stringifyJSON(obj);
```
### ✅ **_toCamelCase**
Converts kebab-case or snake_case to camelCase.
```ts
_toCamelCase('hello_world'); // helloWorld
```
---
## Date & Time Functions
### ✅ **_calculateTimeDifference**
Returns difference between two dates in readable format.
```ts
_calculateTimeDifference(start, end); // "1d 2h 3m 4s"
```
### ✅ **_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);
```
### ✅ **_formatDate**
Formats a date based on a custom pattern.
```ts
_formatDate(new Date(), 'YMD'); // e.g., "Apr 9, 2025"
```
### ✅ **_formatInternationalDate**
Formats a date according to locale, timezone, and preset or custom format.
```ts
const formatted = _formatInternationalDate('2024-07-09T10:00:00Z', {
country: 'IN',
timezone: 'Asia/Kolkata',
format: 'DATETIME_SHORT',
}); // "9/7/2024, 3:30 pm"
```
### ✅ **_getFinancialYear**
Returns the current financial year based on today's date.
```ts
const fy = _getFinancialYear();
```
### ✅ **_getStartStopTime**
Returns the start and end datetime of a given date's month in specified format.
```ts
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
```
### ✅ **_globalizeDateTime**
Converts a date/time to a specific time zone and format.
```ts
const localized = _globalizeDateTime('2024-07-09T12:00:00', {
timeZone: 'Asia/Kolkata',
format: 'yyyy-MM-dd HH:mm',
}); // "2024-07-09 17:30"
```
### ✅ **_isLeapYear**
Determines whether a given year is a leap year based on calendar rules.
```ts
const isLeap = _isLeapYear(2024); // true
```
### ✅ **_isWeekend**
Checks if a given date falls on a weekend (Saturday or Sunday).
```ts
const weekend = _isWeekend(new Date('2025-06-08')); // true (Sunday)
```
---
### ✅ **_calPercentage**
Calculates the percentage of a value relative to total.
```ts
_calPercentage(40, 200); // 20
```
### ✅ **_convertToCurrency**
Converts a number to a formatted currency string.
```ts
const price = _convertToCurrency(2500, 'INR');
```
### ✅ **_getPriceAfterTax**
Adds tax to a given price.
```ts
_getPriceAfterTax(100, 18); // 118
```
### ✅ **_thousandSeparator**
Formats a number with thousand separators and fixed decimal precision.
```ts
const formatted = _thousandSeparator(1234567.89);
```
---
### ✅ **_alert**
Shows a customizable alert modal.
```ts
await _alert({ title: "Test", text: "Data save successfully!" });
```
### ✅ **_asyncDebounce**
Debounces an async function call.
```ts
const debouncedFn = _asyncDebounce(fetchData, 500);
debouncedFn();
```
### ✅ **_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
}
```
### ✅ **_dynamicReducer**
Creates a simple dynamic reducer using generic action handler logic.
```ts
const reducer = _dynamicReducer(initialState);
```
### ✅ **_generateUUID**
Generates a unique UUID string using the browser's `crypto` API.
```ts
const id = _generateUUID();
console.log(id); // e.g., "3b12f1df-5232-4e6b-8f36-3a4e5f7f8b84"
```
### ✅ **_genericReducer**
A generic reducer accepting predefined handlers for each action type.
```ts
const reducer = _genericReducer(initialState, customActions);
```
### ✅ **_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)
);
```
### ✅ **_handleChildrenMenu**
Recursively sets assigned state and permissions of child nodes.
```ts
_handleChildrenMenu(menuList, parentKey, checked);
```
### ✅ **_handleParentNode**
Recursively updates parent permissions based on child permissions.
```ts
_handleParentNode(menuList, menuId, permissionKey);
```
### ✅ **_handleParentsMenu**
Recursively updates parent menu's assigned state and permissions based on children.
```ts
_handleParentsMenu(menuList, menuId);
```
### ✅ **_handleSafe**
Executes a synchronous or asynchronous action safely, handling errors and an optional `finally` block without breaking the application.
```ts
await _handleSafe(
async () => {
await someAsyncTask();
},
(error) => {
console.error('Error occurred:', error);
},
() => {
console.log('Cleanup after execution');
}
);
```
### ✅ **_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([]);
```
### ✅ **_log**
Logs a styled message to the console with a specified log level (`log`, `info`, `warn`, `error`).
```ts
_log("UserService", "Fetching user details...", "info");
```
### ✅ **_sleep**
Creates a delay for a given time using Promise.
```ts
await _sleep(1000); // Wait 1 second
```
### ✅ **_throwError**
Throws an error with an optional context object and logs it to the console.
```ts
_throwError("Something went wrong");
```
###
**Approved by** : [**NPM Community**](https://docs.npmjs.com/policies/open-source-terms)
**License** : [**MIT**](https://docs.npmjs.com/policies/npm-license) © 2022–2024
---