Package Exports
- react-js-plugins
- react-js-plugins/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (react-js-plugins) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
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:
npm install react-js-plugins
# or
pnpm add react-js-pluginsAuthors
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!
✅ createAxiosInstance
Creates a preconfigured instance for authenticated API calls. It supports automatic date formatting, optional data encryption/decryption, seamless data transformation, enhanced security, and built-in error handling with full cross-browser compatibility.
const apiPrivate = createAxiosInstance({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 30000,
withCredentials: true,
enableDateTransform: true,
transformRequest: (data) => transform(data),
transformResponse: (data) => transform(data),
handleAuthError: async (instance, originalRequest, error) => {
console.error('API Error:', error.message);
},
});✅ _arrayDiff
Returns the difference between two arrays.
const diff = _arrayDiff(['a', 'b'], ['b']); // ['a']✅ _arrayIncludesObject
Checks if array contains object (by value).
_arrayIncludesObject(arr, obj);✅ _arrayIntersection
Returns common elements between two arrays.
_arrayIntersection([1,2,3], [2,3,4]); // [2,3]✅ _arrayToObject
Converts array of key-value pairs to object.
_arrayToObject([['a', 1], ['b', 2]]); // { a: 1, b: 2 }✅ _arrayToObjectByKey
Converts array of objects to object using a key.
_arrayToObjectByKey(users, 'id');✅ _asyncMap
Async map over array items one by one.
const results = await _asyncMap(ids, fetchById);✅ _average
Calculates the average of numbers in an array.
_average([4, 8]); // 6✅ _batchProcess
Processes an array of data in asynchronous batches.
await _batchProcess(myArray, 10, async (item) => {
await handleItem(item);
});✅ _chunk
Splits an array into chunks of a given size.
const parts = _chunk([1, 2, 3, 4], 2); // [[1,2], [3,4]]✅ _deepCloneArray
Deeply clones an array of objects.
const cloned = _deepCloneArray(originalArray);✅ _deepCompareArrays
Checks if two arrays are deeply equal.
const isEqual = _deepCompareArrays(arr1, arr2);✅ _extractKeyValues
Extracts all non-undefined values for a specific key from an array.
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.
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.
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.
const enabledUsers = _filterArrayByKeyValue(userList, "isActive", true);✅ _filterByMatchedKey
Filters list1 based on matching key values from list2.
const filtered = _filterByMatchedKey(usersList, activeUsers, "userId");✅ _filterByMatchingKey
Filters list1 by comparing the key's value in list2, with more validation than _filterByMatchedKey.
const filtered = _filterByMatchingKey(productList, inStockItems, "productId");✅ _filterDuplicates
Removes duplicates based on a specific object key.
const unique = _filterDuplicates(users, 'id');✅ _findObjectById
Finds an object in an array by its id.
const item = _findObjectById(items, '123');✅ _flattenArray
Flattens nested arrays by recursively extracting item.data if present.
const flat = _flattenArray(nestedArray);✅ _flattenArrayByKey
Flattens an array of objects by extracting and combining values from a specified key.
_flattenArrayByKey([{ id: 1, items: ['a', 'b'] }, { id: 2, items: ['c'] }], 'items');
// ['a', 'b', 'c']✅ _getArrayOfObjectsByProperty
Returns all objects with a specific property value.
_getArrayOfObjectsByProperty(data, 'type', 'active');✅ _getMaxMinValue
Finds the max and min values in an array.
const { max, min } = _getMaxMinValue([5, 2, 9]);✅ _getUniqueValues
Returns an array of unique values.
const unique = _getUniqueValues([1, 2, 2, 3]);✅ _groupBy
Groups array items by a given key.
const grouped = _groupBy(users, 'department');✅ _hasElement
Searches recursively in a menu tree to find an element by key and value.
const found = _hasElement(menuItems, "id", 5);✅ _hasItem
Searches recursively in a menu tree to find an item by path.
const item = _hasItem(menuItems, "/dashboard");✅ _isEmptyArray
Checks if a given value is an empty array.
const isEmpty = _isEmptyArray([]);✅ _isInArray
Checks if a value exists in array.
_isInArray(['a', 'b'], 'b'); // true✅ _isValueInArray
Checks whether a value exists in a given array.
const exists = _isValueInArray([1, 2, 3], 2);✅ _mapAsync
Parallel async map over array.
const data = await _mapAsync(users, fetchDetails);✅ _mergeArrays
Merges two arrays and removes duplicates.
const merged = _mergeArrays(arr1, arr2);✅ _mergeArraysByKey
Merges two arrays of objects based on a common key.
const merged = _mergeArraysByKey(arr1, arr2, 'id');✅ _removeFalsy
Removes all falsy values (false, 0, '', null, undefined, NaN) from an array.
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.
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.
const cleaned = _removeDuplicates(data, 'email');✅ _sortByKey
Sorts array of objects by a specific key.
const sorted = _sortByKey(products, 'price');✅ _sum
Returns the sum of an array of numbers.
_sum([1, 2, 3]); // 6✅ _swapArrayByKey
Sorts an array in descending order based on a key.
const sorted = _swapArrayByKey(data, 'score');✅ _swapArrayElements
Swaps two elements in an array.
_swapArrayElements(arr, 0, 1);✅ _transformArray
Applies a transformation function to each item in an array.
const result = _transformArray(users, user => user.name);✅ _transformAsyncData
Applies a transformer to each array item asynchronously.
const updated = await _transformAsyncData(data, transformFn);✅ _updateObjectInArray
Updates a matching object in an array by key-value.
const updated = _updateObjectInArray(users, 'id', '123', { name: 'New Name' });✅ _deepClone
Deep clones an object using JSON.stringify and JSON.parse.
const clone = _deepClone(originalObj);✅ _deepEqual
Deep comparison between two objects.
const isSame = _deepEqual(objA, objB);✅ _deepMerge
Recursively merges two objects.
const merged = _deepMerge(obj1, obj2);✅ _filterObjectByKey
Filters object based on allowed keys.
_filterObjectByKey(user, ['id', 'name']);✅ _flattenObject
Flattens a nested object into dot notation key-value pairs.
const flat = _flattenObject({ a: { b: 1 } }); // { 'a.b': 1 }✅ _freeze
Freezes an object to make it immutable.
const frozen = _freeze(config);✅ _getKeyByValue
Returns the first key in an object with the matching value.
const key = _getKeyByValue(obj, 'targetValue');✅ _getKeysByValue
Finds all keys in an object with a specific value.
const keys = _getKeysByValue(obj, 'active');✅ _getNestedProperty
Retrieves value from object using a string path.
const value = _getNestedProperty(user, 'profile.name');✅ _getObjectValues
Returns object values as an array.
_getObjectValues({ a: 1, b: 2 }); // [1, 2]✅ _getValueByKey
Returns the value of a key from an object.
const value = _getValueByKey(obj, 'username');✅ _isEmptyObject
Checks if an object has no own properties.
const isObjEmpty = _isEmptyObject({});✅ _isEqual
Checks deep equality of two values using JSON.stringify.
const isSame = _isEqual(obj1, obj2);✅ _isFreeze
Checks if object is frozen.
_isFreeze(obj); // true/false✅ _isSeal
Checks if object is sealed.
_isSeal(obj); // true/false✅ _mapObject
Maps over an object and returns an array using a callback.
const result = _mapObject(myObj, (key, value) => `${key}: ${value}`);✅ _mergeObjects
Merges two objects, giving priority to the second object's properties.
const merged = _mergeObjects(obj1, obj2);✅ _objectToArray
Converts object to array of key-value pairs.
_objectToArray({ a: 1 }); // [['a', 1]]✅ _seal
Seals an object to prevent adding/removing properties.
_seal(settings);✅ _setNestedProperty
Sets a deeply nested property in an object using a string path.
_setNestedProperty(obj, 'user.address.city', 'Mumbai');✅ _dynamicRequiredValidation
Generates a Yup schema with required validations for given fields.
const schema = _dynamicRequiredValidation(['name', 'email']);✅ _generateYupValidation
Creates a Yup validation schema with all fields marked as required.
const schema = _generateYupValidation(['name', 'age']);✅ _initializeFormikFields
Returns an object with default empty string values for Formik fields.
const formikFields = _initializeFormikFields(['username', 'password']);✅ _initializeFormValues
Initializes form values with empty strings for each field.
const initialValues = _initializeFormValues(['name', 'email']);✅ _isValidForm
Validates a Formik form and returns whether it's valid.
const isValid = await _isValidForm(formRef);✅ _setTouchedFields
Marks all fields with errors as touched in a Formik form.
_setTouchedFields(formRef, errors);✅ _validateFormRef
Returns form validity and error details from a Formik ref.
const { isValid, errors } = await _validateFormRef(formRef);✅ _isValidBase64
Checks if a string is a valid Base64-encoded value.
const isValid = _isValidBase64('U29tZSB0ZXh0');✅ _isValidBlob
Checks if the input is a Blob.
const isValid = _isValidBlob(new Blob(['text']));✅ _isValidBoolean
Checks if the input is a boolean.
const isValid = _isValidBoolean(true);✅ _isValidCreditCard
Checks if a string matches known credit card patterns.
const isValid = _isValidCreditCard('4111111111111111');✅ _isValidDate
Checks if a string matches the YYYY-MM-DD date format.
const isValid = _isValidDate('2025-04-09');✅ _isValidDateObject
Checks if the input is a valid Date object.
const isValid = _isValidDateObject(new Date());✅ _isValidDateRange
Checks if the start date is earlier than or equal to the end date.
const isValid = _isValidDateRange('2025-01-01', '2025-12-31');✅ _isValidDateTime
Checks if a string matches the YYYY-MM-DDTHH:mm:ss format.
const isValid = _isValidDateTime('2025-04-09T12:30:00');✅ _isValidDateString
Checks if the string can be parsed as a valid date.
const isValid = _isValidDateString('2025-04-09');✅ _isValidEmail
Checks if a string is a valid email address.
const isValid = _isValidEmail('user@example.com');✅ _isValidEvent
Checks if the input is an instance of Event.
const isValid = _isValidEvent(new Event('click'));✅ _isValidFile
Checks if the input is a File.
const isValid = _isValidFile(new File([''], 'file.txt'));✅ _isValidFormData
Checks if the input is a FormData instance.
const isValid = _isValidFormData(new FormData());✅ _isValidFunction
Checks if the input is a valid function.
const isValid = _isValidFunction(() => {});✅ _isValidHexColor
Checks if a string is a valid hex color code.
const isValid = _isValidHexColor('#FF5733');✅ _isValidHTMLCollection
Checks if the input is an HTMLCollection.
const isValid = _isValidHTMLCollection(document.forms);✅ _isValidHTMLElement
Checks if the input is an instance of HTMLElement.
const isValid = _isValidHTMLElement(document.body);✅ _isValidIP
Checks if a string is a valid IPv4 address.
const isValid = _isValidIP('192.168.1.1');✅ _isValidJSON
Checks if a string is valid JSON.
const isValid = _isValidJSON('{"name":"John"}');✅ _isValidMacAddress
Checks if a string is a valid MAC address.
const isValid = _isValidMacAddress('00:1A:2B:3C:4D:5E');✅ _isValidNode
Checks if the input is a Node.
const isValid = _isValidNode(document.createTextNode('text'));✅ _isValidNodeList
Checks if the input is a NodeList.
const isValid = _isValidNodeList(document.querySelectorAll('div'));✅ _isValidNumber
Checks if the input is a valid number.
const isValid = _isValidNumber(123.45);✅ _isValidPassword
Checks if a password has 8+ characters, at least 1 letter and 1 number.
const isValid = _isValidPassword('Abc12345');✅ _isValidPhoneNumber
Checks if a string is a valid international phone number (10–15 digits).
const isValid = _isValidPhoneNumber('+919876543210');✅ _isValidPromise
Checks if the input is a Promise.
const isValid = _isValidPromise(Promise.resolve());✅ _isValidRegExp
Checks if the input is a regular expression.
const isValid = _isValidRegExp(/abc/);✅ _isValidString
Checks if the input is a non-empty string.
const isValid = _isValidString('Hello');✅ _isValidTime
Checks if a string is a valid 24-hour HH:mm format.
const isValid = _isValidTime('23:59');✅ _isValidURL
Checks if a string is a valid URL format.
const isValid = _isValidURL('https://example.com');✅ _isValidURLSearchParams
Checks if the input is a URLSearchParams instance.
const isValid = _isValidURLSearchParams(new URLSearchParams());✅ _isValidUsername
Checks if a username is 3+ characters and contains only letters, numbers, dots, underscores, or hyphens.
const isValid = _isValidUsername('john_doe');✅ _isValidUUID
Checks if a string is a valid UUID (v1 to v5).
const isValid = _isValidUUID('550e8400-e29b-41d4-a716-446655440000');✅ _isTruncate
Checks if text would be truncated based on the character limit.
_isTruncate('This is a long text example', 10);
// Returns: true✅ _encryptJson
Encrypts a JSON object using AES encryption with a secret key.
const encrypted = _encryptJson({ name: "John" }, "secret123");✅ _decryptJson
Decrypts AES-encrypted JSON string using a secret key.
const decrypted = _decryptJson(encryptedString, "secret123");✅ _encryptString
Encrypts a plain string using AES encryption, with optional random IV.
const result = _encryptString("mySecretText", "secretKey");✅ _decryptString
Decrypts an AES-encrypted string using the provided IV and secret key.
const plainText = _decryptString(ciphertext, iv, "secretKey");✅ _encrypt
Encrypts a full JSON payload using a random key and IV, both of which are secured by a main secret key. This ensures that each encryption produces a unique ciphertext, even for the same input data.
const encryptedPayload = _encrypt({ userId: 101, role: "admin" }, "mainSecretKey");
/*
Returns:
{
data: "<AES-encrypted JSON payload>",
header: "<Encrypted random key & IV using mainSecretKey>",
iv: "<Base64 IV used for header encryption>"
}
*/✅ _decrypt
Securely decrypts a payload that was encrypted using _encrypt.
It first decrypts the header (which contains the AES key and IV), then uses those to decrypt the main payload.
const decryptedPayload = _decrypt(encryptedPayload, "mainSecretKey");
/*
Returns:
{ userId: 101, role: "admin" }
*/✅ _encryptData
Encrypts payload or data using AES encryption with a static IV.
const result = _encryptData({
data: { userId: 123, role: "admin" },
secretKey: "Base64EncodedSecretKey",
iv: "Base64EncodedIV"
});✅ _decryptData
Decrypts encrypted data (produced by _encryptData) back into the original string or object.
const result = _decryptData({
data: "U2FsdGVkX1+wZyF1ZmFjN1pnWlZ5YVhT0sw==",
secretKey: "Base64EncodedSecretKey",
iv: "Base64EncodedIV"
});✅ _escapeHTML
Escapes special HTML characters to prevent injection or rendering issues.
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.
const newPassword = _generatePassword(12);✅ _addEventListenerToElement
Attaches an event listener to a DOM element.
_addEventListenerToElement('#my-btn', 'click', handleClick);✅ _allowAlphaKeys
Allows only alphabetic input and valid control keys.
<input onKeyDown={_allowAlphaKeys} />✅ _allowAlphaNumericKeys
Allows only alphanumeric keys during typing.
document.addEventListener('keydown', _allowAlphaNumericKeys);✅ _allowDecimalKeys
Allows only decimal input and valid control keys.
<input onKeyDown={_allowDecimalKeys} />✅ _clearNode
Hides specific sibling DOM nodes relative to a base element.
_clearNode('.my-element', [{ type: 'previous', steps: 1 }]);✅ _cloneElement
Clones a DOM element.
const clone = _cloneElement('.to-clone');✅ _domSelector
Selects a single or all DOM elements matching a CSS selector.
const el = _domSelector('#myElement');
const elements = _domSelector('.list-item', true);✅ _getChildElements
Returns child elements of a selector.
const children = _getChildElements('.container');✅ _getElementAttribute
Gets the value of an element's attribute.
const id = _getElementAttribute('.item', 'data-id');✅ _getElementsByClass
Returns elements with a given class.
const elements = _getElementsByClass('my-class');✅ _getElementsByTag
Returns elements with a given tag name.
const buttons = _getElementsByTag('button');✅ _getParent
Returns parent of a DOM element.
const parent = _getParent('.child');✅ _getScrollPosition
Returns current window scroll position.
const { scrollX, scrollY } = _getScrollPosition();✅ _handlePasteAlphabetKeys
Prevents pasting non-alphabetic characters.
<input onPaste={_handlePasteAlphabetKeys} />✅ _handlePasteDecimalKeys
Prevents pasting invalid decimal values.
<input onPaste={_handlePasteDecimalKeys} />✅ _hideElement
Hides a DOM element by setting its display style to 'none'.
_hideElement('#modal');✅ _insertHTML
Injects HTML at a specific position.
_insertHTML('#box', 'beforeend', '<div>Hello</div>');✅ _isDocumentLoaded
Checks if the document has fully loaded.
if (_isDocumentLoaded()) { /* safe to run code */ }✅ _isElementInViewport
Checks if element is visible in viewport.
const isVisible = _isElementInViewport('.my-element');✅ _isElementPresent
Checks if an element exists in the DOM.
const exists = _isElementPresent('.my-element');✅ _onDOMLoad
Executes the callback when the DOM is fully parsed, but before images and other resources are necessarily loaded.
_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).
_onFullReload(() => {
console.log('Page was fully reloaded.');
});✅ _onWindowLoad
Executes the callback when the entire window is fully loaded, including all images and assets.
_onWindowLoad(() => {
console.log('Window fully loaded!');
});✅ _reloadAfterLoad
Reloads page after a delay post-load.
_reloadAfterLoad(3000); // Reload 3s after load✅ _removeAllChildren
Clears all child nodes of an element.
_removeAllChildren('#container');✅ _removeElement
Removes the first matched DOM element from the document.
_removeElement('#banner');✅ _removeElementAttribute
Removes an attribute from an element.
_removeElementAttribute('.item', 'data-id');✅ _removeEventListenerFromElement
Removes a specific event listener.
_removeEventListenerFromElement('#my-btn', 'click', handleClick);✅ _removeNode
Removes all matched DOM elements from the document.
_removeNode('.temp-item');✅ _removeSafeElement
Safely removes an element if it exists and has a parent.
_removeSafeElement('#popup');✅ _replaceContent
Replaces inner HTML of an element.
_replaceContent('#content', '<p>New content</p>');✅ _runOnIframeLoad
Runs a callback when iframe finishes loading.
_runOnIframeLoad('#myIframe', () => console.log('Loaded'));✅ _scrollToElement
Scrolls smoothly to an element.
_scrollToElement('#target');✅ _scrollToTop
Scrolls the page smoothly to the top.
_scrollToTop();✅ _setElementAttribute
Sets an attribute on a DOM element.
_setElementAttribute('.item', 'data-id', '123');✅ _setElementDisabled
Enables or disables a DOM element.
_setElementDisabled('#submit-btn', true);✅ _setMultipleStyles
Applies multiple CSS styles to an element.
_setMultipleStyles('.card', { color: 'red', fontWeight: 'bold' });✅ _showElement
Displays a hidden DOM element using the provided displayType (default is 'block').
_showElement('#modal');
_showElement('#modal', 'flex');✅ _base64ToBlob
Converts a base64-encoded string into a Blob object.
const blob = _base64ToBlob(base64String);✅ _downloadBase64File
Downloads any base64-encoded data as a file with a specified filename and extension.
const base64Image = 'iVBORw0KGgoAAAANSUhEUgAAA...';
downloadBase64File(base64Image, 'my-picture.png');
const base64PDF = 'JVBERi0xLjQKJeLjz9MNCjEgMCBvYmoK...';
downloadBase64File(base64PDF, 'invoice.pdf');✅ _downloadBlob
Triggers download of a Blob object.
_downloadBlob(blob, 'myfile.pdf');✅ _exportExcel
Exports JSON data to an Excel or CSV file.
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.
const base64 = await _fileToBase64(file);✅ _uint8ArrayToBlob
Converts a Uint8Array into a Blob object with the specified MIME type.
const blob = _uint8ArrayToBlob(uint8Array, 'application/pdf');✅ _octetToBlob
Converts raw binary data (ArrayBuffer, Uint8Array, or number[]) into a Blob object.
Useful for handling octet-stream responses from APIs.
const blob = _octetToBlob(arrayBuffer, 'image/png');✅ _importExcel
Imports data from an Excel file.
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.
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.
_navigate('/about', { state: { user: 'sia' }, replace: true });✅ _go
Navigates through the history stack by a specified number of steps.
_go(-2); // Go back 2 pages
_go(1); // Go forward 1 page✅ _goBack
Navigates to the previous page in history.
_goBack(); // Equivalent to browser back button✅ _goForward
Navigates to the next page in history.
_goForward(); // Equivalent to browser forward button✅ _getCurrentPath
Returns the current pathname from the navigation state.
_getCurrentPath(); // e.g., "/about"✅ _getCurrentState
Returns the current navigation state object.
_getCurrentState(); // e.g., { user: 'sia' }✅ _getLocation
Returns both the current path and state as an object.
_getLocation(); // e.g., { pathname: "/about", state: { user: 'sia' } }✅ _getTypedState
Returns the current navigation state with TypeScript type safety.
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.
_clearRouteState('/dashboard');✅ _findExactRoute
Finds an exact route match from an array of routes based on a pathname.
_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.
const success = await _copyText("Hello, clipboard!");
if (success) {
console.log("Text copied successfully");
}✅ _getBrowserInfo
Returns the name of the browser (e.g., Chrome, Firefox).
const browser = _getBrowserInfo();✅ _getCookie
Retrieves a cookie value by its name.
const token = _getCookie('auth_token');✅ _getQueryString
Returns the query string from the current URL, supporting both ?search and #hash?search formats.
const query = _getQueryString();
console.log('Query string:', query); // Example: ?id=123✅ _getStorage
Handles local/session storage actions like GET, SET, REMOVE, CLEAR.
const data = _getStorage({ action: 'GET', type: 'local', key: 'user' });✅ _isMobile
Detects if the current device is a mobile device.
const mobile = _isMobile();✅ _pasteText
Retrieves and returns the current text content from the clipboard, using modern APIs with a fallback for older browsers.
const text = await _pasteText();
if (text) {
console.log("Pasted text:", text);
}✅ _setCookie
Sets a cookie with a name, value, and expiry (in days).
_setCookie('auth_token', 'abc123', 7);✅ _bytesToSize
Converts byte size into a human-readable format.
const size = _bytesToSize(1024); // "1 KB"✅ _capitalize
Capitalizes the first character of a string.
const name = _capitalize("john"); // "John"✅ _truncateText
Truncates text to a specified character limit and adds ellipsis if truncated.
_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.
const wordCount = _countWords(' Hello world! How are you? '); // 5✅ _decodeURI
Decodes an encoded URI component back to its original readable string format.
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.
const encoded = _encodeURI('hello world@2024'); // 'hello%20world%402024'✅ _escapeRegExpMatch
Escapes special characters for regex matching.
const escaped = _escapeRegExpMatch('a+b*c');✅ _isExactMatch
Checks if a string contains an exact word match using regex.
const match = _isExactMatch('The quick brown fox', 'quick');✅ _parseJSON
Safely parses a JSON string into an object.
const obj = _parseJSON(jsonString);✅ _stringifyJSON
Safely converts an object to a JSON string.
const str = _stringifyJSON(obj);✅ _toCamelCase
Converts kebab-case or snake_case to camelCase.
_toCamelCase('hello_world'); // helloWorld✅ _calculateTimeDifference
Returns difference between two dates in readable format.
_calculateTimeDifference(start, end); // "1d 2h 3m 4s"✅ _dateFormat
Formats a date using Moment.js with the specified format.
const formatted = _dateFormat(new Date(), 'YYYY-MM-DD');✅ _dateTransformer
Recursively formats all dates in an object or array.
const result = _dateTransformer(data);✅ _formatDate
Formats a date based on a custom pattern.
_formatDate(new Date(), 'YMD'); // e.g., "Apr 9, 2025"✅ _formatInternationalDate
Formats a date according to locale, timezone, and preset or custom format.
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.
const fy = _getFinancialYear();✅ _getStartStopTime
Returns the start and end datetime of a given date's month in specified format.
const { startTime, stopTime } = _getStartStopTime(new Date());✅ _getUTCTimestamp
Returns the UTC timestamp.
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.
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.
const isLeap = _isLeapYear(2024); // true✅ _isWeekend
Checks if a given date falls on a weekend (Saturday or Sunday).
const weekend = _isWeekend(new Date('2025-06-08')); // true (Sunday)✅ _calPercentage
Calculates the percentage of a value relative to total.
_calPercentage(40, 200); // 20✅ _convertToCurrency
Converts a number to a formatted currency string.
const price = _convertToCurrency(2500, 'INR');✅ _getPriceAfterTax
Adds tax to a given price.
_getPriceAfterTax(100, 18); // 118✅ _thousandSeparator
Formats a number with thousand separators and fixed decimal precision.
const formatted = _thousandSeparator(1234567.89);✅ _alert
Shows a customizable alert modal.
await _alert({ title: "Test", text: "Data save successfully!" });✅ _asyncDebounce
Debounces an async function call.
const debouncedFn = _asyncDebounce(fetchData, 500);
debouncedFn();✅ _confirm
Shows a customizable confirm modal.
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.
const reducer = _dynamicReducer(initialState);✅ _UUID / _generateUUID
Generates a unique UUID string using the browser's crypto API.
const id = _UUID();
console.log(id); // e.g., "3b12f1df-5232-4e6b-8f36-3a4e5f7f8b84"✅ _genericReducer
A generic reducer accepting predefined handlers for each action type.
const reducer = _genericReducer(initialState, customActions);✅ _handleApi
Wraps an API call with success and error handling, executing the appropriate callback based on the result.
_handleApi(
getDetails({ name: 'sia' }),
(res) => console.log(res),
(err) => console.error(err)
);✅ _handleChildrenMenu
Recursively sets assigned state and permissions of child nodes.
_handleChildrenMenu(menuList, parentKey, checked);✅ _handleParentNode
Recursively updates parent permissions based on child permissions.
_handleParentNode(menuList, menuId, permissionKey);✅ _handleParentsMenu
Recursively updates parent menu's assigned state and permissions based on children.
_handleParentsMenu(menuList, menuId);✅ _handleSafe
Executes a synchronous or asynchronous action safely, handling errors and an optional finally block without breaking the application.
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 ''.
const isEmpty = _isNotEmpty([]);✅ _log
Logs a styled message to the console with a specified log level (log, info, warn, error).
_log("UserService", "Fetching user details...", "info");✅ _sleep
Creates a delay for a given time using Promise.
await _sleep(1000); // Wait 1 second✅ _throwError
Throws an error with an optional context object and logs it to the console.
_throwError("Something went wrong");Approved by : NPM Community
License : MIT © 2022–2024




