gm-utility
v3.0.0
Published
GM Utility
Downloads
595
Maintainers
Readme
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"]
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'
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!