@bondsports/general
v0.2.13
Published
general
Downloads
2,814
Maintainers
Keywords
Readme
@bondsports/general
Overview
The General package is a utility module that centralizes essential constants, enums, interfaces, and functions, providing a unified set of tools for use across multiple projects. By standardizing these utilities, the package ensures consistency, reduces redundancy, and simplifies development. It allows developers to focus on core business logic while relying on a robust foundation of reusable, maintainable, and efficient functions.
Installation
You can install the @bondsports/general
package via npm:
npm install @bondsports/general
- Constants
- Enums
- Array Functions
- String Functions
- Random Functions
- Price Functions
- samePrice
- biggerPrice
- biggerAmount
- validateAmount
- validatePrice
- validatePrices
- validateAmounts
- toFixed
- roundPriceCents
- roundQuantity
- sameQuantity
- calculatePriceFromTotal
- calculatePriceWithTax
- calculateTotalPriceWithTax
- calculateItemUnitPrice
- calculateUnitPriceFromTotal
- calculateQuantityFromTotal
- calculateUnitTax
- convertCentsToDollars
- getRoundingSplit
- splitPriceAmount
- calculateTotalPriceByPriceField
- calculateTotalPriceByPrices
- calculateTotalQuantity
- calculateDue
- calculateItemDue
- General Functions
Constants
Overview
The consts.ts
file defines various constants that are used throughout the application to standardize operations such as processing arrays, handling quantities, formatting prices, and limiting string lengths. These constants help ensure consistency and reliability across different modules.
DEFAULT_CHUNK_SIZE
Description: The default chunk size used for parallelizing array processing.
Value:
10
Usage Example:
import { DEFAULT_CHUNK_SIZE } from '@bondsports/general'; const chunks = splitArrayIntoChunks(dataArray, DEFAULT_CHUNK_SIZE);
DEFAULT_QUANTITY
Description: The default quantity value.
Value:
1
Usage Example:
import { DEFAULT_QUANTITY } from '@bondsports/general'; function calculateTotal(quantity = DEFAULT_QUANTITY) { return quantity * pricePerItem; }
PRICE_DECIMAL_PLACES
Description: The number of decimal places used for prices.
Value:
2
Usage Example:
import { PRICE_DECIMAL_PLACES } from '@bondsports/general'; function formatPrice(price: number) { return price.toFixed(PRICE_DECIMAL_PLACES); }
QUANTITY_DECIMAL_PLACES
Description: The number of decimal places used for quantity values.
Value:
5
Usage Example:
import { QUANTITY_DECIMAL_PLACES } from '@bondsports/general'; function formatQuantity(quantity: number) { return quantity.toFixed(QUANTITY_DECIMAL_PLACES); }
STRING_DEFAULT_LIMIT
Description: The default limit for strings.
Value:
255
Usage Example:
import { STRING_DEFAULT_LIMIT } from '@bondsports/general'; function validateStringLength(str: string) { return str.length <= STRING_DEFAULT_LIMIT; }
Enums
Overview
The enums.ts
file defines several enumerations (enums) that are used throughout the application. These enums help to standardize values and provide clarity when dealing with common statuses, HTTP status codes, and pricing fields.
PromiseStatusEnum
Description: Enum representing the status of a promise.
Values:
FULFILLED = 'fulfilled'
REJECTED = 'rejected'
Usage Example:
import { PromiseStatusEnum } from '@bondsports/general'; function handlePromiseStatus(status: PromiseStatusEnum) { if (status === PromiseStatusEnum.FULFILLED) { console.log('The promise was fulfilled.'); } else if (status === PromiseStatusEnum.REJECTED) { console.error('The promise was rejected.'); } }
HttpStatus
Description: Enum representing the HTTP status codes.
Values:
- Includes common HTTP status codes such as:
OK = 200
CREATED = 201
BAD_REQUEST = 400
NOT_FOUND = 404
INTERNAL_SERVER_ERROR = 500
- Includes common HTTP status codes such as:
Usage Example:
import { HttpStatus } from '@bondsports/general'; function handleHttpResponse(status: HttpStatus) { switch (status) { case HttpStatus.OK: console.log('Request was successful.'); break; case HttpStatus.NOT_FOUND: console.error('Resource not found.'); break; case HttpStatus.INTERNAL_SERVER_ERROR: console.error('Internal server error.'); break; default: console.error('Unhandled status code:', status); } }
PriceFieldEnum
Description: Enum representing the fields used for pricing.
Values:
PRICE = 'price'
TOTAL_PRICE = 'totalPrice'
AMOUNT = 'amount'
PAID_AMOUNT = 'paidAmount'
FEE_AMOUNT = 'feeAmount'
REFUND_AMOUNT = 'refundAmount'
DISCOUNT_AMOUNT = 'discountAmount'
DISPLAY_FULL_PRICE = 'displayFullPrice'
DISPLAY_TOTAL_PRICE_WITH_TAX = 'displayTotalPriceWithTax'
Usage Example:
import { PriceFieldEnum } from '@bondsports/general'; function calculateFieldTotal(items: any[], field: PriceFieldEnum) { return items.reduce((sum, item) => sum + item[field], 0); } const items = [ { price: 100, totalPrice: 110 }, { price: 200, totalPrice: 220 } ]; const total = calculateFieldTotal(items, PriceFieldEnum.TOTAL_PRICE); console.log('Total Price:', total); // Output: Total Price: 330
Array Functions
Overview
The array.util.ts
file provides a collection of utility functions designed to manipulate and manage arrays. These functions include operations for flattening nested structures, filtering unique items, and conditionally inserting elements into arrays.
recursiveFlattenArray
Description: Recursively flattens an array of objects based on the specified properties.
Parameters:
array
: The array to flatten.properties
: The properties to flatten the array based on.
Returns: The flattened array.
Usage Example:
import { recursiveFlattenArray } from '@bondsports/general'; const nestedArray = [{ id: 1, children: [{ id: 2, children: [] }] }]; const flatArray = recursiveFlattenArray(nestedArray, ['children']); console.log(flatArray); // Output: [{ id: 1, children: [{ id: 2, children: [] }] }, { id: 2, children: [] }]
recursiveFlattenObject
Description: Recursively flattens an object by extracting specified properties.
Parameters:
entity
: The object to be flattened.properties
: The properties to be extracted from the object.
Returns: An array of flattened objects.
Usage Example:
import { recursiveFlattenObject } from '@bondsports/general'; const nestedObject = { id: 1, children: { id: 2, children: {} } }; const flatObject = recursiveFlattenObject(nestedObject, ['children']); console.log(flatObject); // Output: [{ id: 1, children: { id: 2, children: {} } }, { id: 2, children: {} }]
insertIf
Description: Inserts elements into an array if a condition is true.
Parameters:
condition
: The condition to check....elements
: The elements to insert into the array.
Returns: The resulting array.
Usage Example:
import { insertIf } from '@bondsports/general'; const items = [ ...insertIf(true, 1, 2, 3), ...insertIf(false, 1, 2, 3) ]; console.log(items); // Output: [1, 2, 3]
uniqueIds
Description: Returns an array of unique IDs from the provided arrays of IDs.
Parameters:
idsArrays
: Arrays of IDs to be merged and filtered.
Returns: An array of unique IDs.
Usage Example:
import { uniqueIds } from '@bondsports/general'; const ids = uniqueIds([1, 2, 3], [3, 4, 5]); console.log(ids); // Output: [1, 2, 3, 4, 5]
uniqueItems
Description: Returns an array of unique items from multiple arrays.
Parameters:
arrays
: The arrays to merge and extract unique items from.
Returns: An array of unique items.
Usage Example:
import { uniqueItems } from '@bondsports/general'; const items = uniqueItems([1, 2, 3], [2, 3, 4], [4, 5, 6]); console.log(items); // Output: [1, 2, 3, 4, 5, 6]
uniqueObjectsList
Description: Returns an array of unique objects by given keys from multiple object arrays.
Parameters:
groupKeys
: The unique keys we want to extract objects by.arrays
: The arrays to merge and extract unique items from.
Returns: An array of unique objects.
Usage Example:
import { uniqueObjectsList } from '@bondsports/general'; const objects = [ { id: 1, name: 'John' }, { id: 2, name: 'Jane' }, { id: 1, name: 'John' } ]; const uniqueObjects = uniqueObjectsList(['id'], objects); console.log(uniqueObjects); // Output: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]
arraysEquals
Description: Checks if multiple arrays are equal to the first array.
Parameters:
firstArray
: The first array to compare....arrays
: Additional arrays to compare.
Returns: Returns true if all arrays are equal, false otherwise.
Usage Example:
import { arraysEquals } from '@bondsports/general'; const isEqual = arraysEquals([1, 2, 3], [1, 2, 3], [1, 2, 3]); console.log(isEqual); // Output: true
isArrayEmpty
Description: Checks if an array is empty.
Parameters:
array
: The array to check.
Returns: True if the array is empty, false otherwise.
Usage Example:
import { isArrayEmpty } from '@bondsports/general'; const emptyCheck = isArrayEmpty([]); console.log(emptyCheck); // Output: true
insertToMapArray
Description: Inserts a value into an array within a map, using the specified key. If the key does not exist in the map, a new array is created and associated with the key.
Parameters:
map
: The map to insert the value into.key
: The key to associate the value with.value
: The value to insert into the array.
Returns: None.
Usage Example:
import { insertToMapArray } from '@bondsports/general'; const map = new Map(); insertToMapArray(map, 'key1', 'value1'); console.log(map.get('key1')); // Output: ['value1']
arrayToMap
Description: Transforms an array of entities with an
id
field into a Map withid
as a key and the entity as a value.Parameters:
array
: The array of entities to transform.
Returns: The resulting Map with
id
as a key and the entity as a value.Usage Example:
import { arrayToMap } from '@bondsports/general'; const entities = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]; const map = arrayToMap(entities); console.log(map.get(1)); // Output: { id: 1, name: 'John' }
isIntersecting
Description: Checks if two arrays have any common elements.
Parameters:
array
: The first array to compare.other
: The second array to compare.
Returns: True if the arrays have common elements, false otherwise.
Usage Example:
import { isIntersecting } from '@bondsports/general'; const hasCommon = isIntersecting([1, 2, 3], [3, 4, 5]); console.log(hasCommon); // Output: true
String Functions
Overview
The string.util.ts
file provides a set of utility functions designed to manipulate and validate strings. These functions include operations for converting strings to title case, generating random strings, formatting names, trimming whitespace, and validating JSON data.
titleCase
Description: Converts a string to title case.
Parameters:
text
: The input string.
Returns: The string converted to title case.
Usage Example:
import { titleCase } from '@bondsports/general'; const title = titleCase('hello world'); console.log(title); // Output: "Hello World"
generateRandomString
Description: Generates a random string based on the provided seed, length, and character set.
Parameters:
seed
: The seed value used for generating the random string.length
: The length of the random string to be generated.charSet
: The character set from which the random string will be composed.
Returns: The randomly generated string.
Usage Example:
import { generateRandomString } from '@bondsports/general'; const randomString = generateRandomString('seed', 10, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'); console.log(randomString); // A random 10-character string
fullName
Description: Generates a full name by combining first name and last name.
Parameters:
firstName
: The first name (optional).lastName
: The last name (optional).
Returns: The full name as a string.
Usage Example:
import { fullName } from '@bondsports/general'; const name = fullName('John', 'Doe'); console.log(name); // Output: "John Doe"
trimString
Description: Trims leading and trailing whitespace from a string.
Parameters:
text
: The string to trim.
Returns: The trimmed string, or
null
if the input string is empty ornull
.Usage Example:
import { trimString } from '@bondsports/general'; const trimmed1 = trimString(' Hello World '); console.log(trimmed1); // Output: "Hello World" const trimmed2 = trimString(' '); console.log(trimmed2); // Output: null
isJSON
Description: Checks if the given data is a valid JSON string.
Parameters:
data
: The data to be checked.
Returns: A boolean indicating whether the data is a valid JSON string.
Usage Example:
import { isJSON } from '@bondsports/general'; const valid = isJSON('{"name": "John"}'); console.log(valid); // Output: true
isString
Description: Checks if a value is a string.
Parameters:
value
: The value to check.
Returns: Returns
true
if the value is a string,false
otherwise.Usage Example:
import { isString } from '@bondsports/general'; const check = isString('Hello World'); console.log(check); // Output: true
Random Functions
Overview
The random.util.ts
file provides utility functions for generating pseudo-random numbers. These functions include generating random numbers with an optional seed value and creating a seeded pseudo-random number generator using the MurmurHash3 algorithm.
murmurHash3Generator
Description: Generates a seeded pseudo-random number generator using the MurmurHash3 algorithm.
Parameters:
seed
: The seed for the pseudo-random number generator.
Returns: A function that generates pseudo-random numbers.
Usage Example:
import { murmurHash3Generator } from '@bondsports/general'; const randomGenerator = murmurHash3Generator('my-seed'); const randomNumber = randomGenerator(); console.log(randomNumber); // Output: A pseudo-random number based on the seed
randomNumber
Description: Generates a random number between the specified range.
Parameters:
max
: The maximum value of the range (inclusive).min
: The minimum value of the range (default: 0).seed
: An optional seed value to generate a deterministic random number.
Returns: A function that, when called, generates a random number within the specified range.
Usage Example:
import { randomNumber } from '@bondsports/general'; const getRandomNumber = randomNumber(100, 0, 'my-seed'); console.log(getRandomNumber()); // Output: A deterministic random number between 0 and 100
Price Functions
Overview
The price.util.ts
file provides a collection of utility functions focused on handling and validating prices and quantities. These functions include operations for comparing prices, validating amounts, rounding values, and calculating totals.
samePrice
Description: Checks if two prices are the same.
Parameters:
firstPrice
: The first price to compare.secondPrice
: The second price to compare.
Returns:
True
if the prices are the same,false
otherwise.Usage Example:
import { samePrice } from '@bondsports/general'; const isSame = samePrice(10.00, 10.00); console.log(isSame); // Output: true
biggerPrice
Description: Checks if the first price is greater than the second price.
Parameters:
bigger
: The bigger price.smaller
: The smaller price.
Returns:
True
if the first price is greater than the second price,false
otherwise.Usage Example:
import { biggerPrice } from '@bondsports/general'; const isBigger = biggerPrice(15.00, 10.00); console.log(isBigger); // Output: true
biggerAmount
Description: Checks if the first amount is greater than the second amount.
Parameters:
bigger
: The bigger amount.smaller
: The smaller amount.
Returns:
True
if the first amount is greater than the second amount,false
otherwise.Usage Example:
import { biggerAmount } from '@bondsports/general'; const isBigger = biggerAmount(5.94, 3.17); console.log(isBigger); // Output: true
validateAmount
Description: Validates that an amount is valid (not null or undefined).
Parameters:
amount
: The amount to validate.
Returns:
True
if the amount is valid,false
otherwise.Usage Example:
import { validateAmount } from '@bondsports/general'; validateAmount(99.99); // Return: true validateAmount(-10.00); // Return: true validateAmount(0); // Return: true validateAmount(null); // Return: false
validatePrice
Description: Validates that a price is valid (greater than or equal to zero).
Parameters:
price
: The price to validate.
Returns:
True
if the price is valid,false
otherwise.Usage Example:
import { validatePrice } from '@bondsports/general'; validatePrice(20.00); // Return: true validatePrice(0); // Return: true validatePrice(-5.00); // Return: false
validatePrices
Description: Validates an array of prices, checking if each price is valid (greater than or equal to zero).
Parameters:
prices
: An array of prices to validate.
Returns:
True
if all prices are valid,false
otherwise.Usage Example:
import { validatePrices } from '@bondsports/general'; const arePricesValid = validatePrices([10.00, 20.00, 30.00]); console.log(arePricesValid); // Output: true
validateAmounts
Description: Validates an array of amounts, checking if each price is valid (not null or undefined).
Parameters:
amounts
: An array of amounts to validate.
Returns:
True
if all amounts are valid,false
otherwise.Usage Example:
import { validateAmounts } from '@bondsports/general'; const areAmountsValid = validateAmounts([10.00, -20.00, 30.00]); console.log(areAmountsValid); // Output: true
toFixed
Description: Rounds a number to a specified precision and returns the result.
Parameters:
num
: The number to round.precision
: The number of decimal places to round to.
Returns: The rounded number.
Usage Example:
import { toFixed } from '@bondsports/general'; const roundedNumber = toFixed(10.123456, 3); console.log(roundedNumber); // Output: 10.123
roundPriceCents
Description: Rounds the price to the nearest cent.
Parameters:
price
: The price to round.
Returns: The rounded price.
Usage Example:
import { roundPriceCents } from '@bondsports/general'; const roundedPrice = roundPriceCents(10.123); console.log(roundedPrice); // Output: 10.12
roundQuantity
Description: Rounds the given quantity to the specified decimal places.
Parameters:
amount
: The amount to round.
Returns: The rounded amount.
Usage Example:
import { roundQuantity } from '@bondsports/general'; const roundedQty = roundQuantity(5.67891); console.log(roundedQty); // Output: 5.67891
sameQuantity
Description: The function checks if two quantities are equal.
Parameters:
firstQuantity
: The first quantity to compare.secondQuantity
: The second quantity to compare.
Returns: Returns
true
if the quantities are approximately equal (i.e., their difference is less than0.0001
), otherwise returnsfalse
.Usage Example:
import { sameQuantity } from '@bondsports/general'; const quantity1 = 5.00001; const quantity2 = 5.000012; const areQuantitiesEqual = sameQuantity(quantity1, quantity2); console.log(areQuantitiesEqual); // Output: true
calculatePriceFromTotal
Description: Calculates the price from the total price, taking into account the quantity and optional tax percentage.
Parameters:
price
: The price per unit.taxPercent
: The tax percentage (optional).quantity
: The quantity (default:DEFAULT_QUANTITY
).
Returns: The calculated price.
Usage Example:
import { calculatePriceFromTotal } from '@bondsports/general'; const price = calculatePriceFromTotal(110, 10); console.log(price); // Output: 100.00
calculatePriceWithTax
Description: Calculates the price with tax.
Parameters:
price
: The price of the item.taxPercent
: The tax percentage to apply (optional).quantity
: The quantity of items (default:DEFAULT_QUANTITY
).
Returns: The calculated price with tax.
Usage Example:
import { calculatePriceWithTax } from '@bondsports/general'; const priceWithTax = calculatePriceWithTax(100, 10, 2); console.log(priceWithTax); // Output: 220.00
calculateTotalPriceWithTax
Description: Calculates the total price of an item including tax.
Parameters:
price
: The price of the item.isTaxInclusive
: Whether the price already includes tax.taxPercent
: The tax percentage to apply, ifisTaxInclusive
isfalse
.quantity
: The quantity of items (default:DEFAULT_QUANTITY
).
Returns: The total price, including tax.
Usage Example:
import { calculateTotalPriceWithTax } from '@bondsports/general'; const totalPrice = calculateTotalPriceWithTax(100, false, 10); console.log(totalPrice); // Output: 110.00
calculateItemUnitPrice
Description: Calculates the item unit price based on the given unit price, tax-inclusive status, and tax percentage.
Parameters:
unitPrice
: The unit price before tax.isTaxInclusive
: A flag indicating whether the price includes tax.taxPercent
: The tax percentage.
Returns: The calculated unit price.
Usage Example:
import { calculateItemUnitPrice } from '@bondsports/general'; const unitPrice = calculateItemUnitPrice(100, true, 10); console.log(unitPrice); // Output: 90.91
calculateUnitPriceFromTotal
Description: Calculates the unit price based on the given total price, tax-inclusive status, tax percentage, and quantity.
Parameters:
totalPrice
: The total price.isTaxInclusive
: A flag indicating whether the price includes tax.taxPercent
: The tax percentage.quantity
: The quantity of items (default:DEFAULT_QUANTITY
).
Returns: The calculated unit price.
Usage Example:
import { calculateUnitPriceFromTotal } from '@bondsports/general'; const unitPrice = calculateUnitPriceFromTotal(330, true, 10, 3); console.log(unitPrice); // Output: 110.00
calculateQuantityFromTotal
Description: Calculates the quantity based on the total amount, unit price, and tax percentage.
Parameters:
totalAmount
: The total amount.unitPrice
: The unit price of the item.isTaxInclusive
: Indicates whether the tax is included in the unit price.taxPercentage
: The tax percentage (optional).
Returns: The calculated quantity.
Usage Example:
import { calculateQuantityFromTotal } from '@bondsports/general'; const quantity = calculateQuantityFromTotal(110, 100, true, 10); console.log(quantity); // Output: 1.00
calculateUnitTax
Description: Calculates the unit tax based on the unit price, tax inclusiveness, and tax percentage.
Parameters:
unitPrice
: The unit price.isTaxInclusive
: Indicates whether the tax is included in the unit price.taxPercent
: The tax percentage.
Returns: The calculated unit tax.
Usage Example:
import { calculateUnitTax } from '@bondsports/general'; const unitTax = calculateUnitTax(100, true, 10); console.log(unitTax); // Output: 9.09
convertCentsToDollars
Description: Converts the given price in cents to dollars.
Parameters:
price
: The price in cents.
Returns: The price in dollars.
Usage Example:
import { convertCentsToDollars } from '@bondsports/general'; const dollars = convertCentsToDollars(10000); console.log(dollars); // Output: 100.00
getRoundingSplit
Description: Calculates the rounding split between a requested price and an actual price.
Parameters:
requestedPrice
: The requested price.price
: The actual price.
Returns: An object containing the number of splits and the split amount.
Usage Example:
import { getRoundingSplit } from '@bondsports/general'; const roundingSplit = getRoundingSplit(100.05, 100); console.log(roundingSplit); // Output: { splitsNumber: 5, splitAmount: 0.01 }
splitPriceAmount
Description: Splits the given amount into multiple parts.
Parameters:
amount
: The amount to be split.splitsNumber
: The number of splits to be made (default: 1).
Returns: An array of numbers representing the split amounts.
Usage Example:
import { splitPriceAmount } from '@bondsports/general'; const splits = splitPriceAmount(100, 3); console.log(splits); // Output: [33.33, 33.33, 33.34]
calculateTotalPriceByPriceField
Description: Calculates the total price by a specified price field in an array of items.
Parameters:
items
: The array of items.startPrice
: The starting price (default:0
).priceField
: The price field to use for calculation (default:PriceFieldEnum.PRICE
).
Returns: The total price.
Usage Example:
import { calculateTotalPriceByPriceField } from '@bondsports/general'; const items = [{ price: 100 }, { price: 200 }, { price: 300 }]; const totalPrice = calculateTotalPriceByPriceField(items); console.log(totalPrice); // Output: 600.00
calculateTotalPriceByPrices
Description: Calculates the total price by summing up the prices in the given array.
Parameters:
prices
: An array of prices.startPrice
: The starting price for the calculation (default:0
).
Returns: The total price.
Usage Example:
import { calculateTotalPriceByPrices } from '@bondsports/general'; const prices = [100, 200, 300]; const totalPrice = calculateTotalPriceByPrices(prices); console.log(totalPrice); // Output: 600.00
calculateTotalQuantity
Description: Calculates the total quantity by summing up the given quantities.
Parameters:
quantities
: An array of quantities to be summed up.startQuantity
: The starting quantity for the calculation (default:0
).
Returns: The total quantity.
Usage Example:
import { calculateTotalQuantity } from '@bondsports/general'; const quantities = [1, 2, 3]; const totalQty = calculateTotalQuantity(quantities); console.log(totalQty); // Output: 6
calculateDue
Description: Calculates the amount due based on the price and the amount already paid.
Parameters:
price
: The total price of the item.paidAmount
: The amount already paid (default:0
).
Returns: The amount due.
Usage Example:
import { calculateDue } from '@bondsports/general'; const amountDue = calculateDue(100, 50); console.log(amountDue); // Output: 50.00
calculateItemDue
Description: Calculates the amount due for an item based on its price and the amount already paid.
Parameters:
item
: The item, which must have aprice
andpaidAmount
property.
Returns: The amount due for the item.
Usage Example:
import { calculateItemDue } from '@bondsports/general'; const item = { price: 100, paidAmount: 50 }; const amountDue = calculateItemDue(item); console.log(amountDue); // Output: 50.00
General Functions
Overview
The general.util.ts
file provides a versatile set of utility functions designed for general-purpose use across various parts of an application. These functions include operations for handling promises, working with enums, validating values, and performing calculations.
absoluteValue
Description: Calculates the absolute value of a number.
Parameters:
value
: The number to calculate the absolute value of.
Returns: The absolute value of the input number.
Usage Example:
import { absoluteValue } from '@bondsports/general'; const absValue = absoluteValue(-42); console.log(absValue); // Output: 42
promiseAllSettled
Description: Executes multiple promises and returns an array of settled results.
Parameters:
promises
: The promises to execute.
Returns: A promise that resolves to an array of fulfilled values.
Usage Example:
import { promiseAllSettled } from '@bondsports/general'; const promises = [ Promise.resolve(1), Promise.resolve(2), Promise.reject(new Error('Failed')) ]; promiseAllSettled(...promises) .then(results => console.log(results)) .catch(error => console.error(error));
isInEnum
Description: Checks if a value is a valid member of an enum.
Parameters:
enumType
: The enum to check against.value
: The value to check.
Returns:
True
if the value is a valid member of the enum,false
otherwise.Usage Example:
import { isInEnum, HttpStatus } from '@bondsports/general'; const isValid = isInEnum(HttpStatus, 200); console.log(isValid); // Output: true
extractValuesFromEnumArray
Description: Extracts values from an array of enums.
Parameters:
values
: The array of values to extract from.enumType
: The enum type to filter the values against.
Returns: An array of values that are present in the enum.
Usage Example:
import { extractValuesFromEnumArray, HttpStatus } from '@bondsports/general'; const validStatuses = extractValuesFromEnumArray([200, 404, 999], HttpStatus); console.log(validStatuses); // Output: [200, 404]
useConditionalPromise
Description: Executes a promise-based operation conditionally based on a boolean condition.
Parameters:
operation
: The promise-based operation to be executed.condition
: The boolean condition that determines whether to execute the operation or use the fallback.fallback
: An optional fallback function to be executed if the condition is false.
Returns: A promise that resolves to the result of the operation or the fallback function.
Usage Example:
import { useConditionalPromise } from '@bondsports/general'; const operation = () => Promise.resolve('Success'); const fallback = () => 'Fallback'; useConditionalPromise(operation, true, fallback) .then(result => console.log(result)); // Output: 'Success'
validateFieldsToUpdate
Description: Validates the fields to update in an entity object.
Parameters:
classType
: The constructor function of the entity object.entity
: The original entity object.fieldsToUpdate
: The fields to update in the entity object.
Returns:
True
if there are fields to update,false
otherwise.Usage Example:
import { validateFieldsToUpdate } from '@bondsports/general'; class User { id: number; name: string; email: string; } const user = new User(); user.id = 1; user.name = 'John'; user.email = '[email protected]'; const fieldsToUpdate = { name: 'John Doe' }; const isValid = validateFieldsToUpdate(User, user, fieldsToUpdate); console.log(isValid); // Output: true
getClassAttributes
Description: Retrieves the attributes of a class instance.
Parameters:
classType
: The constructor function of the class.
Returns: An array of attribute names.
Usage Example:
import { getClassAttributes } from './general.util'; class Product { id: number; name: string; price: number; } const attributes = getClassAttributes(Product); console.log(attributes); // Output: ['id', 'name', 'price']
parallelize
Description: Executes the given async function in parallel for each item in the array. Returns a promise that resolves to an array of results.
Parameters:
array
: The array of items to process.func
: The async function to execute for each item.chunkSize
: The number of items to process in each chunk (default:DEFAULT_CHUNK_SIZE
).
Returns: A promise that resolves to an array of results.
Usage Example:
import { parallelize } from './general.util'; async function processItems(items: any[]) { const results = await parallelize(items, async (item) => { // some async processing return item; }); console.log(results); }