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:
``
bash
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.
$3
`
javascript
// 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;
`
$3
#### getRandomCharacters
Generates random hex-string
`
javascript
const randomString = StringUtil.getRandomCharacters();
console.log(randomString); // Example: "a3f7c9"
`
#### getSubstring
Extracts a substring from a string using start index and length.
`
javascript
const result = StringUtil.getSubstring('hello', 3, 1);
console.log(result); // Output: "el"
`
#### getStringBetweenStrings
Extracts the substring between two specified substrings within a string.
`
javascript
const result = StringUtil.getStringBetweenStrings('hello developer world', 'hello', 'world');
console.log(result); // Output: "developer"
`
#### getLastNCharacters
Returns the last n
characters of a string.
`
javascript
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.
`
javascript
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.
`
javascript
const lines = StringUtil.splitWordsInLinesByMaxLineLength('hello world', 5);
console.log(lines); // Output: ["hello", "world"]
`
#### capitalizeFirstLetter
Capitalizes the first letter of each word in a string.
`
javascript
const result = StringUtil.capitalizeFirstLetter('hello-world');
console.log(result); // Output: "Hello-World"
`
#### abbreviateString
Generates an abbreviation by taking the first character of each word.
`
javascript
const abbreviation = StringUtil.abbreviateString('La Alta Vita');
console.log(abbreviation); // Output: "LAV"
`
#### getCleanSplit
Splits a string into parts using a specified delimiter.
`
javascript
const parts = StringUtil.getCleanSplit('hello,world', ',');
console.log(parts); // Output: ["hello", "world"]
`
#### extractNumberFromString
Extracts the first number from a given string.
`
javascript
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.
$3
`
javascript
// 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.
$3
$3
Converts a relative URL to an absolute URL.
Example:
`
javascript
UrlUtil.makeAbsolute("/user/login", "https://dev-test.com");
// Output: "https://dev-test.com/user/login"
`
$3
Encodes a URI string into a base64 format.
Example:
`
javascript
UrlUtil.encodeURI("www.test.com/dashboard");
// Output: "d3d3LnRlc3QuY29tL2Rhc2hib2FyZA=="
`
$3
Decodes a base64 encoded string back to its original text.
Example:
`
javascript
UrlUtil.decodeURI("d3d3LnRlc3QuY29tL2Rhc2hib2FyZA==");
// Output: "www.test.com/dashboard"
`
$3
Converts an object into a query string.
Example:
`
javascript
UrlUtil.convertObjectToQueryString({ Name: "John", ID: 1120, Age: 60 });
// Output: "?Name=John&ID=1120&Age=60&"
`
$3
Extracts and reduces relevant information from a request object.
Example:
`
javascript
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
`
$3
Determines if a request is a developer request.
Example:
`
javascript
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.
$3
`
javascript
// 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;
`
$3
$3
Converts an array of objects into a single object, keyed by a specific property.
Example:
`
ts
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' } }
`
$3
Generates an array of numbers within a range.
Example:
`
ts
const range = dsUtilInstance.generateRange(10, 1, 2);
console.log(range);
// Output: [1, 3, 5, 7, 9]
`
$3
Finds the intersection of two arrays.
Example:
`
ts
const result = dsUtilInstance.findIntersection([1, 2, 3], [2, 3, 4]);
console.log(result);
// Output: [2, 3]
`
$3
Extracts a subset of an object based on a set of keys.
Example:
`
ts
const obj = { a: 1, b: 2, c: 3 };
const subset = dsUtilInstance.getObjectSubset(obj, ['a', 'c']);
console.log(subset);
// Output: { a: 1, c: 3 }
`
$3
Finds an object in an array that matches all properties of the target object.
Example:
`
ts
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' }
`
$3
Removes unwanted characters from a string.
Example:
`
ts
const cleanStr = dsUtilInstance.removeUnknownCharacters('abc@#$123');
console.log(cleanStr);
// Output: 'abc123'
`
$3
Rounds all numerical fields in an object to two decimal places.
Example:
`
ts
const obj = { a: 1.2345, b: 2.5678 };
const result = dsUtilInstance.roundNumericalFields(obj);
console.log(result);
// Output: { a: 1.23, b: 2.57 }
`
$3
Counts the frequency of elements in an array.
Example:
`
ts
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 } ]
`
$3
Flattens a nested object into a single-level object.
Example:
`
ts
const nested = { a: { b: { c: 1 } } };
const result = dsUtilInstance.flattenObject(nested);
console.log(result);
// Output: { '.a.b.c': 1 }
`
$3
Splits an array into batches of a specified size.
Example:
`
ts
const result = dsUtilInstance.createBatchFromArray([1, 2, 3, 4, 5], 2);
console.log(result);
// Output: [ [1, 2], [3, 4], [5] ]
`
$3
Finds the closest checkpoint for a given value.
Example:
`
ts
const checkpoints = [10, 20, 30];
const result = dsUtilInstance.convergeValueToCheckpoints(25, checkpoints);
console.log(result);
// Output: 30
`
$3
Rounds a number to a specified number of decimal places.
Example:
`
ts
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.
$3
`
javascript
// 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;
`
$3
$3
Parses the given input date and returns a Moment object or formatted string.
Example:
`
ts
const formattedDate = datetimeUtilInstance.formatDate('2023-12-24');
console.log(formattedDate);// '2023-12-24'
`
$3
Formats a given date into the specified format.
Example:
`
ts
const diff = datetimeUtilInstance.dateDifferenceBetween('2023-12-24', '2023-12-31', 'days');
console.log(diff); // -7
`
$3
Returns the current date and time as a Moment object.
Example:
`
ts
const currentDate = datetimeUtilInstance.now();
console.log(currentDate.format('YYYY-MM-DD HH:mm:ss'));
`
$3
Returns the current date and time as a Moment object.
Example:
`
ts
const newDate = datetimeUtilInstance.addDaysToDate('2024-12-24', 5);
console.log(newDate.format('YYYY-MM-DD')); // Output: '2024-12-29'
`
$3
Checks if a given date is between two other dates.
Example:
`
ts
const isBetween = datetimeUtilInstance.isDateBetween('2024-12-20', '2024-12-30', '2024-12-24');
console.log(isBetween); // Output: true
`
$3
Returns the day of the week (0-6) for the given date.
Example:
`
ts
const dow = datetimeUtilInstance.getDOW('2024-12-24');
console.log(dow); // Output: 2 (Tuesday)
`
$3
Calculates the difference between two dates based on the specified unit of time (default is days).
Example:
`
ts
const diffInDays = datetimeUtilInstance.dateDifferenceBetween('2024-12-24', '2024-12-20');
console.log(diffInDays); // Output: 4
`
$3
Adds a specified delta (in seconds by default) to a given date and returns the result.
Example:
`
ts
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'
`
$3
Returns the maximum (latest) of the two provided Moment objects.
Example:
`
ts
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'
`
$3
Returns the start of the day (midnight) for the given date.
Example:
`
ts
const startOfDay = datetimeUtilInstance.startOfDay('2024-12-24');
console.log(startOfDay); // Output: '2024-12-24 00:00:00'
`
$3
Returns the end of the day (23:59:59) for the given date.
Example:
`
ts
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.
$3
`
javascript
// 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);
`
$3
$3
Sends an email using AWS SES..
Example:
`
ts
await mailer.sendEmail({
email: 'recipient@example.com',
subject: 'Test Email',
body: 'Hello, this is a test email!'
}, true);
`
$3
Sends a raw email.
Example:
`
ts
await mailer.sendRaw('Raw email content');
`
$3
Sends an SMS message.
Example:
`
ts
await mailer.sendSMS({
mobile: '1234567890',
template: 'OTP_TEMPLATE',
var1: '123456'
});
`
$3
Sends a transactional SMS message.
Example:
`
ts
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.
$3
`
javascript
// 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);
`
$3
$3
Encrypts a given string..
Example:
`
ts
const encryptedText = CryptoUtil.encrypt('Hello, World!');
console.log(encryptedText); // 686b7465cbe4642bf973d637fdbc6d87:6a7d67804b3211be407b64466afe663f
`
$3
Decrypts a previously encrypted string.
Example:
`
ts
const decryptedText = CryptoUtil.decrypt('686b7465cbe4642bf973d637fdbc6d87:6a7d67804b3211be407b64466afe663f');
console.log(decryptedText); // Outputs: 'Hello, World!'
`
$3
Masks a portion of a string with a specified character.
Example:
`
ts
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'
`
$3
Generates a SHA-256 hash for a given string.
Example:
`
ts
const hashedText = CryptoUtil.hash('test');
console.log(hashedText); // Outputs: '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'
`
$3
Compares a string with a hash to verify a match.
Example:
`
ts
const text = 'test';
const hash = CryptoUtil.hash(text);
console.log(CryptoUtil.hashCompare(text, hash)); // Outputs: true
`
$3
Generates a token based on numeric input.
Example:
`
ts
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
`
$3
Generates a token with a prefix and UID.
Example:
`
ts
const token = CryptoUtil.getRandomToken('12345', 10);
console.log(token); // Outputs: TTKN:12345:xJe6k7dDj1
`
$3
Encrypts the values of an object.
Example:
`
ts
const input = { key1: 'value1', key2: 'value2' };
const output = CryptoUtil.encryptObject(input); // Outputs: { key1: '814e5b85f6f48a2c92a32c7225e23bea:85e3da7bc4719ad8f45f348c2d9f9816', key2: '4aec7671a4af260eff1c7655fb242837:c621a5ee986ddc1555d426e9cbfe35e1' }
`
$3
Decrypts the values of an object.
Example:
`
ts
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:
1. Fork the repository.
2. Create a feature branch.
3. Commit your changes.
4. 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!