@triproject/helpers
v1.1.19
Published
A collection of helper functions for TypeScript projects.
Readme
@triproject/helpers
A collection of utility helper functions for TypeScript projects.
Installation
npm install @triproject/helpersFeatures
- 📅 Date Utilities - Date formatting and manipulation
- 📁 File Helpers - File name and extension utilities
- 🔢 Luhn Algorithm - Credit card validation and generation
- 📊 Array/Object Helpers - Array and object manipulation utilities
- 🎲 Randomizer - Percentage-based random selection
- 🔤 String Utilities - String manipulation, hashing, and formatting
- 📦 TLV Encoding - Tag-Length-Value encoding/decoding
Usage
Date Utilities
Format and manipulate dates with ease:
import { dateUtil } from '@tri/helpers';
// Format dates
const date = dateUtil(new Date());
date.format('YYYY-MM-DD HH:mm:ss'); // "2024-01-15 10:30:45"
date.format('DD/MM/YYYY'); // "15/01/2024"
// UTC offset
dateUtil(new Date()).utcOffset(7).format('HH:mm:ss');
// Convert to UTC
dateUtil(new Date()).utc().format();
// ISO string
dateUtil(new Date()).toISOString();Format tokens:
YYYY- 4-digit yearYY- 2-digit yearMM- Month (padded)M- Month (not padded)DD- Day (padded)D- Day (not padded)HH- Hour (padded)H- Hour (not padded)mm- Minutes (padded)m- Minutes (not padded)ss- Seconds (padded)s- Seconds (not padded)SSS- MillisecondsZ- Timezone offset
File Helpers
Extract file information from URLs and content types:
import { getFileExtension, getFileName } from '@tri/helpers';
// Get extension from content type
getFileExtension('application/json'); // "json"
getFileExtension('image/png'); // "png"
// Get filename from URL
getFileName('https://example.com/document.pdf'); // "document.pdf"
getFileName('https://example.com/', 'image/png'); // "file.png"Luhn Algorithm
Validate and generate credit card numbers:
import { luhn } from '@tri/helpers';
// Validate credit card numbers
luhn.isValid('4532015112830366'); // true
luhn.isValid('4532015112830367'); // false
// Generate check digit
luhn.generate('453201511283036'); // "4532015112830366"
// Get Luhn remainder
luhn.getRemainder('4532015112830366'); // 0Array/Object Helpers
Powerful array and object manipulation utilities:
import {
sort,
chunkArray,
uniqueArray,
flattenArray,
groupBy,
arrayDifference,
intersection,
removeEmptyValues,
omit,
qs,
} from '@tri/helpers';
// Sort arrays
sort(['banana', 'apple', 'cherry'], 'asc'); // ["apple", "banana", "cherry"]
// Chunk arrays
chunkArray([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]
// Remove duplicates
uniqueArray([1, 2, 2, 3, 3]); // [1, 2, 3]
// Flatten nested arrays
flattenArray([
[1, 2],
[3, 4],
]); // [1, 2, 3, 4]
// Group by property
groupBy(
[
{ id: 1, type: 'A' },
{ id: 2, type: 'A' },
],
'type'
);
// { A: [{ id: 1, type: 'A' }, { id: 2, type: 'A' }] }
// Array operations
arrayDifference([1, 2, 3], [2, 3, 4]); // [1]
intersection([1, 2, 3], [2, 3, 4]); // [2, 3]
// Remove empty values
removeEmptyValues({ a: 1, b: null, c: undefined }); // { a: 1 }
// Omit object properties
omit({ a: 1, b: 2, c: 3 }, ['b']); // { a: 1, c: 3 }
// Convert object to query string
qs({ name: 'John', age: 30 }); // "name=John&age=30"
qs({ user: { name: 'John', age: 30 } }); // "user[name]=John&user[age]=30"Randomizer
Percentage-based random selection:
import { randomizer } from '@tri/helpers';
const items = [
{ id: 'A', percentage: 70 },
{ id: 'B', percentage: 20 },
{ id: 'C', percentage: 10 },
];
const selected = randomizer.withPercentage(items);
// Returns one of the items based on percentage distributionString Utilities
Comprehensive string manipulation and formatting:
import {
generateId,
generateCode,
generateRandomString,
formatCurrency,
maskEmail,
md5,
capitalizeFirstLetter,
normalizeString,
removeSpecialCharacters,
sanitizeSensitiveRequestFromObject,
toCsv,
} from '@tri/helpers';
// Generate unique ID
generateId(); // "251217134835577-Xv-2o5m-Dz"
generateId(7); // With UTC offset
// Generate code with prefix
generateCode('INV'); // "INV202412171234567"
// Random string
generateRandomString(10); // "aB3dE5fG7h"
// Format currency
formatCurrency(1000000); // "Rp1.000.000"
formatCurrency(1000, 'en-US', 'USD'); // "$1,000.00"
// Mask email
maskEmail('[email protected]'); // "u***@example.com"
// MD5 hash
md5('hello'); // returns MD5 hash
// String utilities
capitalizeFirstLetter('hello'); // "Hello"
normalizeString('Hello World'); // "helloworld"
removeSpecialCharacters('Hello, World!'); // "Hello World"
// Sanitize sensitive data
sanitizeSensitiveRequestFromObject({
username: 'user',
password: 'secret',
}); // { username: 'user', password: '*******' }
// Convert to CSV
toCsv(['Name', 'Age'], ['John', '30']); // "Name,Age\nJohn,30"TLV Encoding
Tag-Length-Value encoding for data serialization:
import { encodeTlv, encodeTlvs, decodeTlv } from '@tri/helpers';
// Encode single TLV
encodeTlv('01', 'test'); // "0104test"
// Encode multiple TLVs
encodeTlvs([
['01', 'test'],
['02', 'data'],
]); // "0104test0204data"
// Decode TLV
decodeTlv('0104test0204data'); // { '01': 'test', '02': 'data' }API Reference
Date Utilities
dateUtil(date?: Date | string | number): DateUtil
Creates a DateUtil instance for date manipulation.
Methods:
utcOffset(offsetMinutes: number): DateUtil- Apply UTC offsetutc(): DateUtil- Convert to UTCformat(pattern?: string): string- Format datetoISOString(): string- Get ISO stringtoString(): string- Get default formatted string
File Helpers
getFileExtension(contentType: string): string | undefined
Returns file extension for a given content type.
getFileName(url: string, contentType?: string): string
Extracts filename from URL or generates one based on content type.
Luhn Algorithm
luhn.isValid(value: string): boolean
Validates a number using the Luhn algorithm.
luhn.generate(value: string): string
Generates a valid Luhn number by appending a check digit.
luhn.getRemainder(value: string): number
Returns the Luhn remainder for a given value.
Array/Object Helpers
All array and object manipulation functions are available as named exports.
Randomizer
randomizer.withPercentage<T>(data: T[]): T | undefined
Returns a random item based on percentage distribution.
String Utilities
Comprehensive string manipulation functions including ID generation, formatting, hashing, and more.
TLV Encoding
encodeTlv(tag: string, value: string | string[]): string
Encodes a single tag-value pair.
encodeTlvs(params: [string, string][]): string
Encodes multiple tag-value pairs.
decodeTlv<T>(data: string): Record<T, string>
Decodes TLV-encoded data.
Development
# Install dependencies
npm install
# Run tests
npm test
# Build
npm run buildTesting
The package includes comprehensive test coverage with 195 tests covering all utilities.
npm testLicense
ISC
Author
triyanto
