Package Exports
- super-utilix
Readme
super-utilix
A powerful and comprehensive utility library for TypeScript/JavaScript applications. This package provides a wide range of helper functions for handling dates, objects, arrays, string manipulation, validation, and more.
Installation
npm install super-utilixFeatures
- 📅 Date Utilities: Format dates, calculate age, validate future dates, time conversion, and timestamp helpers.
- 🛠 Object Utilities: Deep comparison, field removal, sorting, form data conversion, and complex object manipulations.
- 🔍 Search & Filter: Recursive search in objects, array filtering, query string generation, and URL parameter handling.
- 🔢 Arabic Utilities: Convert numbers to Arabic ordinal words.
- 📝 DOM & Events: HTML text extraction and keyboard event handlers (Arabic, English, Numbers, Floating Point).
- 🔄 CRUD Helpers: Frontend-side state management for Create, Read, Update, Delete operations.
- ✅ Validation: Date validation helpers.
API Reference
1. Arabic Utilities
literalOrdinals(num, lang)
Convert numbers into their Arabic ordinal representation (e.g., 1 -> الأول).
import { literalOrdinals } from 'super-utilix';
console.log(literalOrdinals(1, 'ar')); // "الأول"
console.log(literalOrdinals(25, 'ar')); // "الخامس والعشرون"2. Date Utilities
formatDateWithPattern(date, format)
Formats a Date object using a custom pattern.
Supported tokens: YYYY, YY, MM, M, DD, D, HH, H, hh, h, mm, m, ss, s, A, a.
import { formatDateWithPattern } from 'super-utilix';
formatDateWithPattern(new Date(), 'YYYY-MM-DD hh:mm A'); // "2023-12-25 02:30 PM"formatDateTime(date, format?)
Formats a date string or object. Default format: DD/MM/YYYY, h:mmA.
import { formatDateTime } from 'super-utilix';
formatDateTime('2023-12-25T14:30:00'); // "25/12/2023, 2:30PM"formatDate(date, format?)
Formats a date string or object. Default format: DD/MM/YYYY.
import { formatDate } from 'super-utilix';
formatDate('2023-12-25'); // "25/12/2023"getTime(inputDate)
Extracts time in HH:mm format from a date.
import { getTime } from 'super-utilix';
getTime('2023-12-25T14:30:00'); // "14:30"isFutureDate(date, start?)
Checks if a date is in the future (compared to tomorrow's start).
date: Date string or object.start: Optional start date. Defaults to tomorrow's start.
calculateDetailedAge(birthDate, t?, currentDate?, gender?)
Calculates detailed age (years, months, days) with localization support.
t: Optional translation function(key: string) => string.currentDate: Defaults to now.gender: Optional gender string for localization.
import { calculateDetailedAge } from 'super-utilix';
const age = calculateDetailedAge('1990-01-01');
console.log(age.message); // "33 years - 11 months - 24 days..."calculateAge(birthDate)
Returns the age in years from a given birth date string.
Supports YYYY-MM-DD and DD/MM/YYYY formats.
import { calculateAge } from 'super-utilix';
calculateAge('1990-01-01'); // 33
calculateAge('01/01/1990'); // 33birthDateToAge(birthDate)
Returns object { years, months, days } from a birth date.
import { birthDateToAge } from 'super-utilix';
console.log(birthDateToAge('1990-01-01'));
// { years: 33, months: 11, days: 24 }ageToBirthDate(age)
Calculates birth date from an age object { years, months, days }.
import { ageToBirthDate } from 'super-utilix';
const birthDate = ageToBirthDate({ years: 30, months: 5, days: 10 });
console.log(birthDate); // Date objectageToBirthDateChangeSegment(oldAge, age)
Calculates a new birth date based on changed age segments.
import { ageToBirthDateChangeSegment } from 'super-utilix';
const newBirthDate = ageToBirthDateChangeSegment(
{ years: 30, months: 0, days: 0 },
{ years: 31, months: 0, days: 0 },
);convertTimeToTimestamp(timeString)
Converts a time string in format "DD HH:mm:ss" (e.g., "01 10:30:00") to milliseconds.
import { convertTimeToTimestamp } from 'super-utilix';
const ms = convertTimeToTimestamp('01 10:30:00');
console.log(ms); // Total milliseconds3. Object Utilities
removeEmptyFields(obj)
Removes fields with null, undefined, or empty string values.
import { removeEmptyFields } from 'super-utilix';
removeEmptyFields({ name: 'Ali', age: null }); // { name: 'Ali' }objectToFormData(obj)
Converts a potentially nested object into a FormData object.
import { objectToFormData } from 'super-utilix';
const formData = objectToFormData({ name: 'Ali', file: new File([], 'test.png') });compareObjects(original, updated, keysToIgnore?)
Deeply compares two objects, optionally ignoring specific keys.
import { compareObjects } from 'super-utilix';
compareObjects({ a: 1 }, { a: 1, b: 2 }, ['b']); // truegetChangedFields(original, updated)
Returns an object containing only the fields that have changed.
import { getChangedFields } from 'super-utilix';
const changes = getChangedFields({ a: 1 }, { a: 2 }); // { a: 2 }capitalizeString(str)
Capitalizes the first letter of a string.
import { capitalizeString } from 'super-utilix';
capitalizeString('hello'); // "Hello"removeIdFromObjects(objects)
Removes _id field from an array of objects.
import { removeIdFromObjects } from 'super-utilix';
const result = removeIdFromObjects([{ _id: '1', name: 'Ali' }]);
// [{ name: 'Ali' }]removeItemsWithIds(array, idsToRemove)
Removes items from an array that match the given IDs.
import { removeItemsWithIds } from 'super-utilix';
const result = removeItemsWithIds([{ _id: '1' }, { _id: '2' }], ['1']);
// [{ _id: '2' }]createOptionsArray(data, valueField, ...labelFields)
Creates an array of options { value, label } for select inputs.
import { createOptionsArray } from 'super-utilix';
const users = [{ id: 1, firstName: 'Ali', lastName: 'Khan' }];
const options = createOptionsArray(users, 'id', 'firstName', 'lastName');
// [{ value: 1, label: "Ali Khan" }]filterUsersOption(option, inputValue)
Filter helper for user select options (matches name or email).
import { filterUsersOption } from 'super-utilix';
// Used in filter logic
const isMatch = filterUsersOption(
{ label: { props: { children: ['Ali', 'ali@example.com'] } } },
'Ali',
);removeKeys(obj, keys)
Removes specified keys from an object.
import { removeKeys } from 'super-utilix';
const result = removeKeys({ a: 1, b: 2 }, ['b']); // { a: 1 }getArrayKeys(obj)
Returns an array of keys that have array values in the object.
import { getArrayKeys } from 'super-utilix';
getArrayKeys({ a: [1, 2], b: 3 }); // [{ a: [1, 2] }]convertObjectToArray(obj)
Converts an object { key: value } into an array [{ key: value }].
import { convertObjectToArray } from 'super-utilix';
convertObjectToArray({ a: 1, b: 2 }); // [{ a: 1 }, { b: 2 }]comparePermissionLists(list1, list2)
Compares two lists of permissions.
import { comparePermissionLists } from 'super-utilix';
const isEqual = comparePermissionLists([{ read: ['users'] }], [{ read: ['users'] }]); // truesortObjectByKeys(obj)
Sorts object keys alphabetically.
import { sortObjectByKeys } from 'super-utilix';
sortObjectByKeys({ b: 2, a: 1 }); // { a: 1, b: 2 }sortObjectByValues(obj)
Sorts object properties by numeric values.
import { sortObjectByValues } from 'super-utilix';
sortObjectByValues({ a: 2, b: 1 }); // { b: 1, a: 2 }removeFields(obj, fieldsToRemove)
Recursively removes specified fields from an object or array.
import { removeFields } from 'super-utilix';
removeFields({ a: 1, nested: { a: 1, b: 2 } }, ['a']);
// { nested: { b: 2 } }removeFieldsTopLevel(obj, fieldsToRemove)
Removes specified fields from an object or array (shallow).
import { removeFieldsTopLevel } from 'super-utilix';
removeFieldsTopLevel({ a: 1, nested: { a: 1 } }, ['a']);
// { nested: { a: 1 } }getLabelByItemsAndId(id, items, fields)
Finds a label from items array by ID.
import { getLabelByItemsAndId } from 'super-utilix';
getLabelByItemsAndId(1, [{ id: 1, name: 'Ali' }], 'name'); // "Ali"getLabelByItemsAndOptions(id, items)
Finds a label from options array ({ value, label }) by ID.
import { getLabelByItemsAndOptions } from 'super-utilix';
getLabelByItemsAndOptions(1, [{ value: 1, label: 'Ali' }]); // "Ali"4. Search & Filter Utilities
searchInObjects(data, query, childrenField, fieldsToSearch?)
Recursively searches through an array of objects (and their children).
import { searchInObjects } from 'super-utilix';
const data = [{ id: 1, name: 'Parent', children: [{ id: 2, name: 'Child' }] }];
const result = searchInObjects(data, 'Child', 'children', ['name']);searchInObjectsWithParents(data, query, childrenField, fieldsToSearch?)
Same as searchInObjects but retains the parent structure for matching children.
import { searchInObjectsWithParents } from 'super-utilix';
const result = searchInObjectsWithParents(data, 'Child', 'children', ['name']);addSearchParam(searchParams, setSearchParams, key, value)
Helper to update URL search parameters.
import { addSearchParam } from 'super-utilix';
// Inside a component or hook
addSearchParam(searchParams, setSearchParams, 'page', '2');filterInArray(field, values, data)
Filters an array of objects based on whether a field's value exists in a provided array.
import { filterInArray } from 'super-utilix';
filterInArray('id', [1, 2], [{ id: 1 }, { id: 3 }]); // [{ id: 1 }]filterInObjects(data, query, childrenField, fieldsToFilter?)
Recursively filters objects based on a query string matching specified fields.
import { filterInObjects } from 'super-utilix';
const result = filterInObjects(data, ['Child'], 'children', ['name']);5. Query String Utilities
toQueryString(params)
Converts an object into a URL query string, removing empty fields.
import { toQueryString } from 'super-utilix';
toQueryString({ page: 1, search: 'test' }); // "page=1&search=test"createSearchQuery(params)
Creates a query string from parameters, handling arrays and primitives.
import { createSearchQuery } from 'super-utilix';
createSearchQuery({ ids: [1, 2], type: 'all' }); // "ids=1&ids=2&type=all"serializeFormQuery(params)
Serializes form params for backend requests.
import { serializeFormQuery } from 'super-utilix';
serializeFormQuery({ ids: [1, 2] }); // "ids=1,2"arrFromQuery(query)
Converts a comma-separated query string back to an array of numbers.
import { arrFromQuery } from 'super-utilix';
arrFromQuery('1,2,3'); // [1, 2, 3]uniqueId()
Generates a unique timestamp-based ID.
import { uniqueId } from 'super-utilix';
console.log(uniqueId()); // 168...pureURLS3(url)
Cleans up S3 URLs to remove query parameters and domain prefix.
import { pureURLS3 } from 'super-utilix';
pureURLS3('http://bucket.s3.com/folder/file.png?token=...'); // "folder/file.png"prePareFilters(searchParams)
Parses and prepares filter parameters from URL search params.
import { prePareFilters } from 'super-utilix';
const filters = prePareFilters(new URLSearchParams('filters=%5B...%5D'));6. Event Handlers (Input Validation)
handleKeyDownNumber
Prevents non-numeric input.
import { handleKeyDownNumber } from 'super-utilix';
<input onKeyDown={handleKeyDownNumber} />handleKeyDownNumberNoCopy
Prevents non-numeric input and disables copy/paste.
import { handleKeyDownNumberNoCopy } from 'super-utilix';
<input onKeyDown={handleKeyDownNumberNoCopy} />handleKeyDownFloatNumber
Allows numbers and one decimal point.
import { handleKeyDownFloatNumber } from 'super-utilix';
<input onKeyDown={handleKeyDownFloatNumber} />handleKeyDownArabic
Restricts input to Arabic characters.
import { handleKeyDownArabic } from 'super-utilix';
<input onKeyDown={handleKeyDownArabic} />handleKeyDownEnglish
Restricts input to English characters.
import { handleKeyDownEnglish } from 'super-utilix';
<input onKeyDown={handleKeyDownEnglish} />7. DOM Utilities
getTextOnlyFromHtml(html)
Extracts plain text from an HTML string.
import { getTextOnlyFromHtml } from 'super-utilix';
getTextOnlyFromHtml('<p>Hello <b>World</b></p>'); // "Hello World"8. CRUD Operations (Frontend)
Helper functions to manage state arrays for Create, Read, Update, Delete.
Usage of CRUD Helpers
import {
handleCreateFront,
handleCreateFrontUnique,
handleUpdateFront,
handleDeleteFront,
} from 'super-utilix';
// Create
handleCreateFront({ items, setItems, itemData: { name: 'New Item' } });
// Create Unique
handleCreateFrontUnique({ items, setItems, itemData, uniqueField: 'id' });
// Update
handleUpdateFront({ id: 1, items, setItems, itemData: { name: 'Updated' } });
// Delete
handleDeleteFront({ id: 1, items, setItems });9. Validation
validateDay(value)
Ensures day is between 1-31.
import { validateDay } from 'super-utilix';
validateDay('32'); // "31"validateMonth(value)
Ensures month is between 1-12.
import { validateMonth } from 'super-utilix';
validateMonth('13'); // "12"validateYear(value)
Ensures year is valid (>= 1900).
import { validateYear } from 'super-utilix';
validateYear('1800'); // "1900"License
ISC