@unidev-hub/core-utils
v0.1.1
Published
Core utilities for Unidev Hub applications
Readme
@unidev-hub/core-utils
Core utilities library for Unidev Hub applications.
📚 Table of Contents
🔧 Installation
Install the package using npm:
npm install @unidev-hub/core-utilsOr using yarn:
yarn add @unidev-hub/core-utils✨ Features
- 📅 Date Utilities: Format, parse, calculate, validate, and manipulate dates
- 🔤 String Utilities: Format, transform, validate, and sanitize strings
- 🔢 Number Utilities: Format, calculate, and convert numbers
- 📋 Array Utilities: Transform, sort, filter, and manipulate arrays
- 🧩 Object Utilities: Clone, merge, and transform objects
- ✅ Validation Utilities: Validate data with common rules
- 🔗 URL Utilities: Parse, build, and manipulate URLs
- 💾 Storage Utilities: Work with localStorage, sessionStorage, and cookies
- 🔐 Security Utilities: Sanitize, encode, and secure data
- 📂 File Utilities: Work with files, formats, and types
All utilities are:
- ✓ Fully typed with TypeScript
- ✓ Tree-shakable (only import what you need)
- ✓ Well-documented with examples
- ✓ Tested for quality and reliability
📖 Usage
You can import utilities by category:
// Import specific category
import { date } from '@unidev-hub/core-utils';
// Use utilities
const formattedDate = date.formatDate(new Date(), 'friendly');Or import specific functions directly:
// Import specific functions
import { formatDate, parseDate } from '@unidev-hub/core-utils/date';
// Use functions
const formattedDate = formatDate(new Date(), 'friendly');
```, calculate, and convert numbers
- 📋 **Array Utilities**: Transform, sort, filter, and manipulate arrays
- 🧩 **Object Utilities**: Clone, merge, and transform objects
- ✅ **Validation Utilities**: Validate data with common rules
- 🔗 **URL Utilities**: Parse, build, and manipulate URLs
- 💾 **Storage Utilities**: Work with localStorage, sessionStorage, and cookies
- 🔐 **Security Utilities**: Sanitize, encode, and secure data
All utilities are:
- ✓ Fully typed with TypeScript
- ✓ Tree-shakable (only import what you need)
- ✓ Well-documented with examples
- ✓ Tested for quality and reliability
## 📖 Usage
You can import utilities by category:
```typescript
// Import specific category
import { date } from '@unidev-hub/core-utils';
// Use utilities
const formattedDate = date.formatDate(new Date(), 'friendly');Or import specific functions directly:
// Import specific functions
import { formatDate, parseDate } from '@unidev-hub/core-utils/date';
// Use functions
const formattedDate = formatDate(new Date(), 'friendly');Date Utilities
import { date } from '@unidev-hub/core-utils';
// Format dates
date.formatDate(new Date(), 'friendly'); // => "April 3, 2025"
date.formatRelativeTime(new Date(Date.now() - 3600000)); // => "1 hour ago"
// Parse dates
date.parseDate('2025-04-03'); // => Date object
date.parseFlexible('04/03/2025'); // => Date object (works with multiple formats)
// Calculate with dates
date.addDays(new Date(), 7); // => Date 7 days from now
date.getDateDifference(date1, date2); // => { days: 5, months: 0, years: 0, ... }
date.getBusinessDays(startDate, endDate); // => 5 (excluding weekends)
// Validate dates
date.isValidDate(new Date()); // => true
date.isDateInFuture(new Date(2030, 0, 1)); // => true
date.isDateInRange(date, startDate, endDate); // => true
// Work with timezones
date.formatInTimezone(new Date(), 'America/New_York'); // => Format in specific timezone
date.getCurrentTimezone(); // => "America/Los_Angeles"String Utilities
import { string } from '@unidev-hub/core-utils';
// Format strings
string.truncate('This is a long string', 10); // => "This is..."
string.formatTemplate('Hello, {name}!', { name: 'John' }); // => "Hello, John!"
// Work with string cases
string.capitalize('hello world'); // => "Hello world"
string.toCamelCase('hello_world'); // => "helloWorld"
string.toSnakeCase('helloWorld'); // => "hello_world"
// Validate strings
string.isEmpty(''); // => true
string.isEmail('[email protected]'); // => true
string.isUrl('https://example.com'); // => true
// Sanitize strings
string.stripHtml('<p>Hello <b>world</b></p>'); // => "Hello world"
string.normalizeWhitespace(' Hello world '); // => "Hello world"
string.toSafeFilename('File: "data" (2023).txt'); // => "File_data_2023.txt"Number Utilities
import { number } from '@unidev-hub/core-utils';
// Format numbers
number.formatNumber(1234567.89, 2); // => "1,234,567.89"
number.formatPercent(0.2567, 2); // => "25.67%"
number.formatBytes(1536); // => "1.50 KB"
// Format currencies
number.formatCurrency(1234.56, 'USD'); // => "$1,234.56"
number.formatCurrency(1234.56, 'EUR', 'de-DE'); // => "1.234,56 €"
// Calculate with numbers
number.round(1.2345, 2); // => 1.23
number.clamp(15, 0, 10); // => 10
number.randomBetween(1, 10); // => Random integer between 1 and 10
// Convert units
number.celsiusToFahrenheit(25); // => 77
number.unitConversions.kilometersToMiles(10); // => 6.21371Array Utilities
import { array } from '@unidev-hub/core-utils';
// Transform arrays
array.unique([1, 2, 2, 3, 3, 3]); // => [1, 2, 3]
array.chunk([1, 2, 3, 4, 5, 6, 7], 3); // => [[1, 2, 3], [4, 5, 6], [7]]
array.flatten([1, [2, 3], [4, [5, 6]]]); // => [1, 2, 3, 4, 5, 6]
// Sort arrays
array.sortBy(users, 'age'); // => Sort users by age
array.sortNumerically([3, 1, 10, 5]); // => [1, 3, 5, 10]
array.sortByDate(events, 'date'); // => Sort events by date
// Filter arrays
array.filterByProperty(users, 'role', 'admin'); // => Users with role 'admin'
array.search(users, 'john', ['name', 'email']); // => Users matching 'john' in name or email
array.paginate(items, 2, 10); // => Page 2 with 10 items per pageObject Utilities
import { object } from '@unidev-hub/core-utils';
// Clone objects
object.shallowClone({ a: 1, b: 2 }); // => { a: 1, b: 2 } (new reference)
object.deepClone({ a: 1, b: { c: 2 } }); // => Deep clone of nested objects
// Merge objects
object.merge({ a: 1 }, { b: 2 }); // => { a: 1, b: 2 }
object.deepMerge({ a: 1, b: { c: 2 } }, { b: { d: 3 } }); // => { a: 1, b: { c: 2, d: 3 } }
// Transform objects
object.pick(user, ['id', 'name', 'email']); // => Only specified properties
object.omit(user, ['password']); // => All properties except 'password'
object.mapKeys(data, key => key.toUpperCase()); // => Transform all keysValidation Utilities
import { validation } from '@unidev-hub/core-utils';
const { rules } = validation;
// Validate with individual rules
rules.required(''); // => 'This field is required'
rules.email('[email protected]'); // => true
rules.minLength(5)('abc'); // => 'Minimum length is 5 characters'
// Combine multiple rules
validation.validate('', [rules.required, rules.email]);
// => 'This field is required'
// Validate objects
const user = { name: '', email: 'invalid' };
const schema = {
name: [rules.required],
email: [rules.required, rules.email]
};
validation.validateObject(user, schema);
// => { name: 'This field is required', email: 'Invalid email format' }URL Utilities
import { url } from '@unidev-hub/core-utils';
// Parse URLs
url.parseUrl('https://example.com:8080/path?query=value#hash');
// => URL object with components
url.parseQueryString('?name=John&age=30');
// => { name: 'John', age: '30' }
// Build URLs
url.buildQueryString({ name: 'John', age: 30 });
// => 'name=John&age=30'
url.addQueryParams('https://example.com', { sort: 'name', page: 2 });
// => 'https://example.com?sort=name&page=2'
url.joinUrl('https://example.com/', '/api/', '/users');
// => 'https://example.com/api/users'Storage Utilities
import { storage } from '@unidev-hub/core-utils';
// Work with localStorage
storage.setLocalItem('user', { id: 1, name: 'John' });
const user = storage.getLocalItem('user');
storage.removeLocalItem('user');
// Work with sessionStorage
storage.setSessionItem('cart', { items: [1, 2, 3] });
const cart = storage.getSessionItem('cart');
// Work with cookies
storage.setCookie('theme', 'dark', { expires: 30, path: '/' });
const theme = storage.getCookie('theme');
// Unified storage API
const { StorageType } = storage;
storage.set('preferences', { theme: 'dark' }, StorageType.LOCAL);
storage.get('preferences', StorageType.LOCAL);
storage.remove('preferences', StorageType.LOCAL);Security Utilities
import { security } from '@unidev-hub/core-utils';
// Sanitize content
security.sanitizeHtml('<p>Hello <script>alert("xss")</script></p>');
// => 'Hello'
security.sanitizeHtmlAllowTags('<p>Hello <b>world</b> <script>alert("xss")</script></p>');
// => '<p>Hello <b>world</b> </p>'
// Encode/decode data
security.encodeBase64('Hello World');
// => 'SGVsbG8gV29ybGQ='
security.decodeBase64('SGVsbG8gV29ybGQ=');
// => 'Hello World'
// Generate UUIDs
security.generateUUID();
// => '123e4567-e89b-42d3-a456-556642440000'
// Mask sensitive data
security.maskString('1234567890', 4, 2);
// => '1234****90'File Utilities
import { file } from '@unidev-hub/core-utils';
// Get file information
file.getFileExtension('document.pdf'); // => "pdf"
file.getBasename('document.pdf'); // => "document"
file.getMimeType('image.png'); // => "image/png"
// Check file types
file.isImageFile('photo.jpg'); // => true
file.isDocumentFile('report.pdf'); // => true
file.isVideoFile('movie.mp4'); // => true
// Format file information
file.formatFileSize(1536000); // => "1.47 MB"
file.formatFileSizeShort(1536000); // => "1.5M"
file.formatFilename('very-long-filename-that-needs-truncation.pdf', 20);
// => "very-long-filena...pdf"
// File operations (browser)
file.blobToBase64(imageBlob).then(base64 => {
console.log(base64); // => "data:image/jpeg;base64,..."
});
file.readFileAsText(textFile).then(text => {
console.log(text); // => File contents as string
});
file.createImageThumbnail(imageFile, 200, 200).then(thumbnailDataUrl => {
image.src = thumbnailDataUrl; // => Display thumbnail
});🔍 TypeScript Support
This library is built with TypeScript and includes comprehensive type definitions for all utilities.
// Types are available for all functions
import { formatDate, DateFormat } from '@unidev-hub/core-utils/date';
// TypeScript will catch invalid formats
const date: DateFormat = 'standard'; // Valid
const invalid: DateFormat = 'wrong'; // Error: Type '"wrong"' is not assignable to type 'DateFormat'🌐 Browser Compatibility
The library is compatible with all modern browsers and IE11+. For older browsers, you may need to include appropriate polyfills.
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
String Utilities
import { string } from '@unidev-hub/core-utils';
// Format strings
string.truncate('This is a long string', 10); // => "This is..."
string.formatTemplate('Hello, {name}!', { name: 'John' }); // => "Hello, John!"
// Work with string cases
string.capitalize('hello world'); // => "Hello world"
string.toCamelCase('hello_world'); // => "helloWorld"
string.toSnakeCase('helloWorld'); // => "hello_world"
// Validate strings
string.isEmpty(''); // => true
string.isEmail('[email protected]'); // => true
string.isUrl('https://example.com'); // => true
// Sanitize strings
string.stripHtml('<p>Hello <b>world</b></p>'); // => "Hello world"
string.normalizeWhitespace(' Hello world '); // => "Hello world"
string.toSafeFilename('File: "data" (2023).txt'); // => "File_data_2023.txt"Number Utilities
import { number } from '@unidev-hub/core-utils';
// Format numbers
number.formatNumber(1234567.89, 2); // => "1,234,567.89"
number.formatPercent(0.2567, 2); // => "25.67%"
number.formatBytes(1536); // => "1.50 KB"
// Format currencies
number.formatCurrency(1234.56, 'USD'); // => "$1,234.56"
number.formatCurrency(1234.56, 'EUR', 'de-DE'); // => "1.234,56 €"
// Calculate with numbers
number.round(1.2345, 2); // => 1.23
number.clamp(15, 0, 10); // => 10
number.randomBetween(1, 10); // => Random integer between 1 and 10
// Convert units
number.celsiusToFahrenheit(25); // => 77
number.unitConversions.kilometersToMiles(10); // => 6.21371Array Utilities
import { array } from '@unidev-hub/core-utils';
// Transform arrays
array.unique([1, 2, 2, 3, 3, 3]); // => [1, 2, 3]
array.chunk([1, 2, 3, 4, 5, 6, 7], 3); // => [[1, 2, 3], [4, 5, 6], [7]]
array.flatten([1, [2, 3], [4, [5, 6]]]); // => [1, 2, 3, 4, 5, 6]
// Sort arrays
array.sortBy(users, 'age'); // => Sort users by age
array.sortNumerically([3, 1, 10, 5]); // => [1, 3, 5, 10]
array.sortByDate(events, 'date'); // => Sort events by date
// Filter arrays
array.filterByProperty(users, 'role', 'admin'); // => Users with role 'admin'
array.search(users, 'john', ['name', 'email']); // => Users matching 'john' in name or email
array.paginate(items, 2, 10); // => Page 2 with 10 items per pageObject Utilities
import { object } from '@unidev-hub/core-utils';
// Clone objects
object.shallowClone({ a: 1, b: 2 }); // => { a: 1, b: 2 } (new reference)
object.deepClone({ a: 1, b: { c: 2 } }); // => Deep clone of nested objects
// Merge objects
object.merge({ a: 1 }, { b: 2 }); // => { a: 1, b: 2 }
object.deepMerge({ a: 1, b: { c: 2 } }, { b: { d: 3 } }); // => { a: 1, b: { c: 2, d: 3 } }
// Transform objects
object.pick(user, ['id', 'name', 'email']); // => Only specified properties
object.omit(user, ['password']); // => All properties except 'password'
object.mapKeys(data, key => key.toUpperCase()); // => Transform all keysValidation Utilities
import { validation } from '@unidev-hub/core-utils';
const { rules } = validation;
// Validate with individual rules
rules.required(''); // => 'This field is required'
rules.email('[email protected]'); // => true
rules.minLength(5)('abc'); // => 'Minimum length is 5 characters'
// Combine multiple rules
validation.validate('', [rules.required, rules.email]);
// => 'This field is required'
// Validate objects
const user = { name: '', email: 'invalid' };
const schema = {
name: [rules.required],
email: [rules.required, rules.email]
};
validation.validateObject(user, schema);
// => { name: 'This field is required', email: 'Invalid email format' }URL Utilities
import { url } from '@unidev-hub/core-utils';
// Parse URLs
url.parseUrl('https://example.com:8080/path?query=value#hash');
// => URL object with components
url.parseQueryString('?name=John&age=30');
// => { name: 'John', age: '30' }
// Build URLs
url.buildQueryString({ name: 'John', age: 30 });
// => 'name=John&age=30'
url.addQueryParams('https://example.com', { sort: 'name', page: 2 });
// => 'https://example.com?sort=name&page=2'
url.joinUrl('https://example.com/', '/api/', '/users');
// => 'https://example.com/api/users'Storage Utilities
import { storage } from '@unidev-hub/core-utils';
// Work with localStorage
storage.setLocalItem('user', { id: 1, name: 'John' });
const user = storage.getLocalItem('user');
storage.removeLocalItem('user');
// Work with sessionStorage
storage.setSessionItem('cart', { items: [1, 2, 3] });
const cart = storage.getSessionItem('cart');
// Work with cookies
storage.setCookie('theme', 'dark', { expires: 30, path: '/' });
const theme = storage.getCookie('theme');
// Unified storage API
const { StorageType } = storage;
storage.set('preferences', { theme: 'dark' }, StorageType.LOCAL);
storage.get('preferences', StorageType.LOCAL);
storage.remove('preferences', StorageType.LOCAL);Security Utilities
import { security } from '@unidev-hub/core-utils';
// Sanitize content
security.sanitizeHtml('<p>Hello <script>alert("xss")</script></p>');
// => 'Hello'
security.sanitizeHtmlAllowTags('<p>Hello <b>world</b> <script>alert("xss")</script></p>');
// => '<p>Hello <b>world</b> </p>'
// Encode/decode data
security.encodeBase64('Hello World');
// => 'SGVsbG8gV29ybGQ='
security.decodeBase64('SGVsbG8gV29ybGQ=');
// => 'Hello World'
// Generate UUIDs
security.generateUUID();
// => '123e4567-e89b-42d3-a456-556642440000'
// Mask sensitive data
security.maskString('1234567890', 4, 2);
// => '1234****90'🔍 TypeScript Support
This library is built with TypeScript and includes comprehensive type definitions for all utilities.
// Types are available for all functions
import { formatDate, DateFormat } from '@unidev-hub/core-utils/date';
// TypeScript will catch invalid formats
const date: DateFormat = 'standard'; // Valid
const invalid: DateFormat = 'wrong'; // Error: Type '"wrong"' is not assignable to type 'DateFormat'🌐 Browser Compatibility
The library is compatible with all modern browsers and IE11+. For older browsers, you may need to include appropriate polyfills.
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
