gm-utility v5.0.0
Utility Package
A versatile utility package providing a wide range of functions for various programming needs. This documentation covers the String-Utility section.
Installation
Install the package via npm:
npm install gm-utility
String Utility
The String-Utility module provides powerful string manipulation functions. Below is a detailed list of available functions, along with examples.
Guide to Import Package ESModule/CommonJS
// Using ES Module (import)
import { Utility } from 'gm-utility';
const StringUtil = Utility.string;
// Using CommonJS (require)
const { Utility } = require('gm-utility');
const StringUtil = Utility.string;
Available Functions
getRandomCharacters
Generates random hex-string
const randomString = StringUtil.getRandomCharacters();
console.log(randomString); // Example: "a3f7c9"
getSubstring
Extracts a substring from a string using start index and length.
const result = StringUtil.getSubstring('hello', 3, 1);
console.log(result); // Output: "el"
getStringBetweenStrings
Extracts the substring between two specified substrings within a string.
const result = StringUtil.getStringBetweenStrings('hello developer world', 'hello', 'world');
console.log(result); // Output: "developer"
getLastNCharacters
Returns the last n
characters of a string.
const result = StringUtil.getLastNCharacters('hello', 2);
console.log(result); // Output: "lo"
splitTextInLinesByLength
Splits a string into multiple lines, with each line having a specified maximum length.
const lines = StringUtil.splitTextInLinesByLength('hello world', 3);
console.log(lines); // Output: ["hel", "lo ", "wor", "ld"]
splitWordsInLinesByMaxLineLength
Splits text into lines by breaking at word boundaries, ensuring each line respects a specified character limit.
const lines = StringUtil.splitWordsInLinesByMaxLineLength('hello world', 5);
console.log(lines); // Output: ["hello", "world"]
capitalizeFirstLetter
Capitalizes the first letter of each word in a string.
const result = StringUtil.capitalizeFirstLetter('hello-world');
console.log(result); // Output: "Hello-World"
abbreviateString
Generates an abbreviation by taking the first character of each word.
const abbreviation = StringUtil.abbreviateString('La Alta Vita');
console.log(abbreviation); // Output: "LAV"
getCleanSplit
Splits a string into parts using a specified delimiter.
const parts = StringUtil.getCleanSplit('hello,world', ',');
console.log(parts); // Output: ["hello", "world"]
extractNumberFromString
Extracts the first number from a given string.
const result = StringUtil.extractNumberFromString('123hello456world');
console.log(result); // Output: "123"
URL Utility NPM Package
A powerful utility package to simplify handling URLs, encode/decode URI strings, manipulate query strings, and extract essential request metadata. Ideal for developers working with HTTP requests and URL manipulations.
Guide to Import Package ESModule/CommonJS
// Using ES Module (import)
import { Utility } from 'gm-utility';
const UrlUtil = Utility.url;
// Using CommonJS (require)
const { Utility } = require('gm-utility');
const UrlUtil = Utility.url;
Features
- Convert relative URLs to absolute URLs.
- Encode and decode strings in base64.
- Convert objects to query strings.
- Extract and reduce essential information from request objects.
- Determine if a request is a developer request.
Available Functions
makeAbsolute(path: string, baseUrl: string): string
Converts a relative URL to an absolute URL.
Example:
UrlUtil.makeAbsolute("/user/login", "https://dev-test.com");
// Output: "https://dev-test.com/user/login"
encodeURI(uri: string): string
Encodes a URI string into a base64 format.
Example:
UrlUtil.encodeURI("www.test.com/dashboard");
// Output: "d3d3LnRlc3QuY29tL2Rhc2hib2FyZA=="
decodeURI(encoded: string): string
Decodes a base64 encoded string back to its original text.
Example:
UrlUtil.decodeURI("d3d3LnRlc3QuY29tL2Rhc2hib2FyZA==");
// Output: "www.test.com/dashboard"
convertObjectToQueryString(obj: object): string
Converts an object into a query string.
Example:
UrlUtil.convertObjectToQueryString({ Name: "John", ID: 1120, Age: 60 });
// Output: "?Name=John&ID=1120&Age=60&"
getReducedRequest(request: object): object
Extracts and reduces relevant information from a request object.
Example:
UrlUtil.getReducedRequest({
body: { name: "John Doe", age: 30 },
params: {},
query: { search: "term" },
headers: { "content-type": "application/json" },
method: "POST",
url: "/example?search=term",
path: "/example",
ip: "127.0.0.1"
});
// Output: Reduced request object
isDeveloperRequest(headers: object, method: string, isDev: boolean): boolean
Determines if a request is a developer request.
Example:
UrlUtil.isDeveloperRequest({ "content-type": "application/json" }, 'POST', true);
// Output: false
Data Structures Utility
A utility library for performing common operations on arrays, objects, and strings. It includes methods for transformations, aggregations, and mathematical operations to simplify your development.
Guide to Import Package ESModule/CommonJS
// Using ES Module (import)
import { Utility } from 'gm-utility';
const DsUtil = Utility.ds;
// Using CommonJS (require)
const { Utility } = require('gm-utility');
const DsUtil = Utility.ds;
Available Functions
transformArrayToObjectByKey<T>(arr: T[], key: keyof T): Record<string, T>
Converts an array of objects into a single object, keyed by a specific property.
Example:
const data = [
{ id: '1', name: 'Alice' },
{ id: '2', name: 'Bob' }
];
const result = dsUtilInstance.transformArrayToObjectByKey(data, 'id');
console.log(result);
// Output: { '1': { id: '1', name: 'Alice' }, '2': { id: '2', name: 'Bob' } }
generateRange(stop: number, start: number = 1, step: number = 1): number[]
Generates an array of numbers within a range.
Example:
const range = dsUtilInstance.generateRange(10, 1, 2);
console.log(range);
// Output: [1, 3, 5, 7, 9]
findIntersection(n: any[], e: any[]): any[]
Finds the intersection of two arrays.
Example:
const result = dsUtilInstance.findIntersection([1, 2, 3], [2, 3, 4]);
console.log(result);
// Output: [2, 3]
getObjectSubset(obj: Record<string, any>, keys: string[]): Record<string, any>
Extracts a subset of an object based on a set of keys.
Example:
const obj = { a: 1, b: 2, c: 3 };
const subset = dsUtilInstance.getObjectSubset(obj, ['a', 'c']);
console.log(subset);
// Output: { a: 1, c: 3 }
findMatchingObjectInArray<T extends Record<string, any>>(obj1: T, arr1: T[]): T | undefined
Finds an object in an array that matches all properties of the target object.
Example:
const data = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ];
const result = dsUtilInstance.findMatchingObjectInArray({ id: 2 }, data);
console.log(result);
// Output: { id: 2, name: 'Bob' }
removeUnknownCharacters(str: string): string
Removes unwanted characters from a string.
Example:
const cleanStr = dsUtilInstance.removeUnknownCharacters('abc@#$123');
console.log(cleanStr);
// Output: 'abc123'
roundNumericalFields<T extends Record<string, unknown>>(e: T): T
Rounds all numerical fields in an object to two decimal places.
Example:
const obj = { a: 1.2345, b: 2.5678 };
const result = dsUtilInstance.roundNumericalFields(obj);
console.log(result);
// Output: { a: 1.23, b: 2.57 }
getElemCountOfArray<T>(d: T[], type: 'object' | 'array'): Record<string, number> | { key: T, frequency: number }[]
Counts the frequency of elements in an array.
Example:
const arr = [1, 2, 2, 3];
const count = dsUtilInstance.getElemCountOfArray(arr, 'array');
console.log(count);
// Output: [ { key: 1, frequency: 1 }, { key: 2, frequency: 2 }, { key: 3, frequency: 1 } ]
flattenObject(obj: Record<string, any>): Record<string, any>
Flattens a nested object into a single-level object.
Example:
const nested = { a: { b: { c: 1 } } };
const result = dsUtilInstance.flattenObject(nested);
console.log(result);
// Output: { '.a.b.c': 1 }
createBatchFromArray<T>(arr: T[], n: number = 50): T[][]
Splits an array into batches of a specified size.
Example:
const result = dsUtilInstance.createBatchFromArray([1, 2, 3, 4, 5], 2);
console.log(result);
// Output: [ [1, 2], [3, 4], [5] ]
convergeValueToCheckpoints(value: number, checkpoints: number[]): number | null
Finds the closest checkpoint for a given value.
Example:
const checkpoints = [10, 20, 30];
const result = dsUtilInstance.convergeValueToCheckpoints(25, checkpoints);
console.log(result);
// Output: 30
roundoff(val: number, decimals: number): number
Rounds a number to a specified number of decimal places.
Example:
const rounded = dsUtilInstance.roundoff(1.234567, 3);
console.log(rounded);
// Output: 1.235
datetime-utils
A utility package for simplifying date and time operations using the moment
library. It provides a set of functions to manipulate and format dates and times easily in JavaScript and TypeScript projects.
Guide to Import Package ESModule/CommonJS
// Using ES Module (import)
import { Utility } from 'gm-utility';
const datetimeUtil = Utility.datetime;
// Using CommonJS (require)
const { Utility } = require('gm-utility');
const datetimeUtil = Utility.datetime;
Available Functions
getDateObj(input: string | Date, format: string = 'YYYY-MM-DD HH:mm:ss'): Moment | string
Parses the given input date and returns a Moment object or formatted string.
Example:
const formattedDate = datetimeUtilInstance.formatDate('2023-12-24');
console.log(formattedDate);// '2023-12-24'
formatDate(input: string | Date, format: string = 'YYYY-MM-DD'): Moment | string
Formats a given date into the specified format.
Example:
const diff = datetimeUtilInstance.dateDifferenceBetween('2023-12-24', '2023-12-31', 'days');
console.log(diff); // -7
now(): Moment
Returns the current date and time as a Moment object.
Example:
const currentDate = datetimeUtilInstance.now();
console.log(currentDate.format('YYYY-MM-DD HH:mm:ss'));
addDaysToDate(input: string | Date, nDays: number, format = 'YYYY-MM-DD HH:mm:ss'): Moment | string
Returns the current date and time as a Moment object.
Example:
const newDate = datetimeUtilInstance.addDaysToDate('2024-12-24', 5);
console.log(newDate.format('YYYY-MM-DD')); // Output: '2024-12-29'
isDateBetween(stDate: string | Moment, enDate: string | Moment, input: string | Moment): string | boolean
Checks if a given date is between two other dates.
Example:
const isBetween = datetimeUtilInstance.isDateBetween('2024-12-20', '2024-12-30', '2024-12-24');
console.log(isBetween); // Output: true
getDOW(input: string | Moment): number
Returns the day of the week (0-6) for the given date.
Example:
const dow = datetimeUtilInstance.getDOW('2024-12-24');
console.log(dow); // Output: 2 (Tuesday)
dateDifferenceBetween(start: Moment | string, end: Moment | string, on: moment.unitOfTime.Diff = 'days'): number
Calculates the difference between two dates based on the specified unit of time (default is days).
Example:
const diffInDays = datetimeUtilInstance.dateDifferenceBetween('2024-12-24', '2024-12-20');
console.log(diffInDays); // Output: 4
addDeltaToMoment(delta = 600, input = moment.now(), deltaDef: DurationConstructor = 'seconds')
Adds a specified delta (in seconds by default) to a given date and returns the result.
Example:
const newDate = datetimeUtilInstance.addDeltaToMoment(600, '2024-12-24', 'seconds');
console.log(newDate.format('YYYY-MM-DD HH:mm:ss')); // Output: '2024-12-24 00:10:00'
getMax(lTime: Moment, rTime: Moment): Moment | null
Returns the maximum (latest) of the two provided Moment objects.
Example:
const maxTime = datetimeUtilInstance.getMax('2024-12-24 12:00:00', '2024-12-24 10:00:00');
console.log(maxTime.format('YYYY-MM-DD HH:mm:ss')); // Output: '2024-12-24 12:00:00'
startOfDay(input: Moment | string, format = 'YYYY-MM-DD HH:mm:ss'): string
Returns the start of the day (midnight) for the given date.
Example:
const startOfDay = datetimeUtilInstance.startOfDay('2024-12-24');
console.log(startOfDay); // Output: '2024-12-24 00:00:00'
endOfDay(input: Moment | string, format = 'YYYY-MM-DD HH:mm:ss'): string
Returns the end of the day (23:59:59) for the given date.
Example:
const endOfDay = datetimeUtilInstance.endOfDay('2024-12-24');
console.log(endOfDay); // Output: '2024-12-24 23:59:59'
Mailer/SMS Utility
A utility package for sending emails and SMS using AWS SES and a third-party SMS provider. It includes methods for sending standard emails, raw emails, SMS messages, and transactional SMS.
Guide to Import Package ESModule/CommonJS
// Using ES Module (import)
import { Utility } from 'gm-utility';
const mailerUtil = Utility.mailer;
// Using CommonJS (require)
const { Utility } = require('gm-utility');
const mailerUtil = Utility.mailer;
const awsKeys = {
AWS_KEY: process.env.AWS_KEY || '',
AWS_SECRET: process.env.AWS_SECRET || '',
AWS_SES_REGION: process.env.AWS_SES_REGION || '',
AWS_FROM: process.env.AWS_FROM || '',
AWS_REPLY: process.env.AWS_REPLY || '',
AWS_API_VERSION: process.env.AWS_API_VERSION || '',
TWOFACTOR_API_URL: process.env.TWOFACTOR_API_URL || '',
TWOFACTOR_ACCESS_KEY: process.env.TWOFACTOR_ACCESS_KEY || '',
TWOFACTOR_TXNSMS_URL: process.env.TWOFACTOR_TXNSMS_URL || '',
};
const MailerUtil = new Utility.mailer(awsKeys);
Available Functions
sendEmail(data: EmailData, isHTML?: boolean): Promise<AWS.SES.SendEmailResponse>
Sends an email using AWS SES..
Example:
await mailer.sendEmail({
email: 'recipient@example.com',
subject: 'Test Email',
body: 'Hello, this is a test email!'
}, true);
sendRaw(mailContent: string): Promise<AWS.SES.SendRawEmailResponse | void>
Sends a raw email.
Example:
await mailer.sendRaw('Raw email content');
sendSMS(msg: SMSMessage): Promise<any>
Sends an SMS message.
Example:
await mailer.sendSMS({
mobile: '1234567890',
template: 'OTP_TEMPLATE',
var1: '123456'
});
sendTxn(data: TxnMessage): Promise<any>
Sends a transactional SMS message.
Example:
await mailer.sendTxn({
mobile: '1234567890',
template: 'TRANSACTION_TEMPLATE',
var1: 'Your transaction is successful'
});
Crypto Utility
A utility library offering a suite of cryptographic and utility functions designed to simplify common string and encryption-related tasks. This package provides reliable methods for encryption, decryption, hashing, string masking, randomization, and token generation.
Guide to Import Package ESModule/CommonJS
// Using ES Module (import)
import { Utility } from 'gm-utility';
const cryptoUtil = Utility.crypto;
// Using CommonJS (require)
const { Utility } = require('gm-utility');
const cryptoUtil = Utility.crypto;
const mockEncryptionConstants = {
DATA_ENCRYPTION_ALGORITHM: process.env.DATA_ENCRYPTION_ALGORITHM,
DATA_ENCRYPTION_KEY: process.env.DATA_ENCRYPTION_KEY,
DATA_ENCRYPTION_IV_32: process.env.DATA_ENCRYPTION_IV_32,
};
const CryptoUtil = new Utility.crypto(mockEncryptionConstants);
Available Functions
encrypt(text: string): string
Encrypts a given string..
Example:
const encryptedText = CryptoUtil.encrypt('Hello, World!');
console.log(encryptedText); // 686b7465cbe4642bf973d637fdbc6d87:6a7d67804b3211be407b64466afe663f
decrypt(encryptedText: string): string
Decrypts a previously encrypted string.
Example:
const decryptedText = CryptoUtil.decrypt('686b7465cbe4642bf973d637fdbc6d87:6a7d67804b3211be407b64466afe663f');
console.log(decryptedText); // Outputs: 'Hello, World!'
mask(text: string, start: number = 4, end: number = text.length, maskChar: string = '*'): string
Masks a portion of a string with a specified character.
Example:
const maskedText = CryptoUtil.mask('abcdefghij');
console.log(maskedText); // Outputs: 'abcd******'
const customMask = CryptoUtil.mask('abcdefghij', 2, 6, '#');
console.log(customMask); // Outputs: 'ab####ghij'
// Outputs: 'hello'
hash(text: string): string
Generates a SHA-256 hash for a given string.
Example:
const hashedText = CryptoUtil.hash('test');
console.log(hashedText); // Outputs: '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'
hashCompare(text: string, hash: string): boolean
Compares a string with a hash to verify a match.
Example:
const text = 'test';
const hash = CryptoUtil.hash(text);
console.log(CryptoUtil.hashCompare(text, hash)); // Outputs: true
getNumberToken(input: string): string
Generates a token based on numeric input.
Example:
const token = CryptoUtil.getNumberToken('7');
console.log(token); // Outputs: a valid token, e.g., 'O' or 'P'
const largeToken = CryptoUtil.getNumberToken('1234567890');
console.log(largeToken); // Outputs: CFHJKMPQZA
getRandomToken(uid: string, length: number): string
Generates a token with a prefix and UID.
Example:
const token = CryptoUtil.getRandomToken('12345', 10);
console.log(token); // Outputs: TTKN:12345:xJe6k7dDj1
encryptObject<T extends Record<string, any>>(obj: T): { [K in keyof T]: string }
Encrypts the values of an object.
Example:
const input = { key1: 'value1', key2: 'value2' };
const output = CryptoUtil.encryptObject(input); // Outputs: { key1: '814e5b85f6f48a2c92a32c7225e23bea:85e3da7bc4719ad8f45f348c2d9f9816', key2: '4aec7671a4af260eff1c7655fb242837:c621a5ee986ddc1555d426e9cbfe35e1' }
decryptObject<T extends Record<string, any>>(obj: { [K in keyof T]: string }): T
Decrypts the values of an object.
Example:
const input = { key1: '814e5b85f6f48a2c92a32c7225e23bea:85e3da7bc4719ad8f45f348c2d9f9816', key2: '4aec7671a4af260eff1c7655fb242837:c621a5ee986ddc1555d426e9cbfe35e1' }
const output = CryptoUtil.decryptObject(input); // Outputs: { key1: 'value1', key2: 'value2' }
Contributions are welcome! Please follow the steps below:
- Fork the repository.
- Create a feature branch.
- Commit your changes.
- Open a pull request.
License
This package is licensed under the ISC License. See the LICENSE file for more details.
Feedback
If you encounter any issues or have suggestions, feel free to create an issue in the repository or reach out.
Happy coding!