Skip to main content

Number Utilities

A collection of utility functions for number operations, calculations, and conversions used throughout the WorkPayCore frontend application.

Core Functions

getTotalAmount(item, key)

Calculates the total sum of a specific numeric property from an array of objects.

Parameters:

  • item (array, optional): Array of objects to sum from (default: [])
  • key (string): The property key to sum

Returns:

  • number: The total sum of the specified property

Example:

const items = [
{ amount: 100, name: 'Item 1' },
{ amount: 250, name: 'Item 2' },
{ amount: 75, name: 'Item 3' },
];

const total = getTotalAmount(items, 'amount');
// Returns: 425

Use Cases:

  • Calculating total invoice amounts
  • Summing payment amounts
  • Aggregating numeric values from data sets

checkIfNumber(value)

Validates if a value is a valid number and returns it, or returns 0 if invalid.

Parameters:

  • value (any): The value to check and convert

Returns:

  • number: The original number if valid, 0 if invalid or NaN

Example:

const result1 = checkIfNumber(42);
// Returns: 42

const result2 = checkIfNumber('not a number');
// Returns: 0

const result3 = checkIfNumber(null);
// Returns: 0

const result4 = checkIfNumber(3.14);
// Returns: 3.14

Use Cases:

  • Safe number validation before calculations
  • Preventing NaN errors in mathematical operations
  • Providing fallback values for invalid inputs

toNumber(val)

Converts various types to numbers with null/undefined safety.

Parameters:

  • val (any): The value to convert to a number

Returns:

  • number: The converted number, or 0 if conversion fails or value is null/undefined

Example:

const result1 = toNumber('123');
// Returns: 123

const result2 = toNumber('123.45');
// Returns: 123.45

const result3 = toNumber(null);
// Returns: 0

const result4 = toNumber(undefined);
// Returns: 0

const result5 = toNumber('abc');
// Returns: 0

const result6 = toNumber(true);
// Returns: 1

const result7 = toNumber(false);
// Returns: 0

Use Cases:

  • Converting form input strings to numbers
  • Safe type conversion from API responses
  • Handling optional numeric values

getOrdinal(n)

Converts a number to its ordinal representation (1st, 2nd, 3rd, etc.).

Parameters:

  • n (number): The number to convert to ordinal

Returns:

  • string: The number with its appropriate ordinal suffix

Example:

const result1 = getOrdinal(1);
// Returns: "1st"

const result2 = getOrdinal(2);
// Returns: "2nd"

const result3 = getOrdinal(3);
// Returns: "3rd"

const result4 = getOrdinal(4);
// Returns: "4th"

const result5 = getOrdinal(21);
// Returns: "21st"

const result6 = getOrdinal(22);
// Returns: "22nd"

const result7 = getOrdinal(23);
// Returns: "23rd"

const result8 = getOrdinal(101);
// Returns: "101st"

const result9 = getOrdinal(0);
// Returns: "0"

const result10 = getOrdinal(-1);
// Returns: "-1"

Use Cases:

  • Displaying ranked lists
  • Showing position in competitions or rankings
  • Formatting dates (1st, 2nd, 3rd of the month)
  • Creating user-friendly ordinal displays

Advanced Usage Examples

Calculating Invoice Totals

const invoiceItems = [
{ description: 'Service A', amount: 1500.0 },
{ description: 'Service B', amount: 750.5 },
{ description: 'Service C', amount: 2250.75 },
];

const subtotal = getTotalAmount(invoiceItems, 'amount');
const tax = subtotal * 0.16; // 16% tax
const total = subtotal + tax;

console.log(`Subtotal: ${subtotal}`);
// Output: Subtotal: 4501.25

Safe Form Data Processing

const formData = {
salary: '5000.50',
bonus: null,
deductions: '250.00',
overtime: undefined,
};

const processedData = {
salary: toNumber(formData.salary), // 5000.50
bonus: toNumber(formData.bonus), // 0
deductions: toNumber(formData.deductions), // 250.00
overtime: toNumber(formData.overtime), // 0
};

const netPay =
processedData.salary +
processedData.bonus -
processedData.deductions +
processedData.overtime;
// Result: 4750.50

Ranking Display

const employees = [
{ name: 'Alice', score: 95 },
{ name: 'Bob', score: 87 },
{ name: 'Charlie', score: 91 },
];

// Sort by score descending
const rankedEmployees = employees
.sort((a, b) => b.score - a.score)
.map((emp, index) => ({
...emp,
rank: getOrdinal(index + 1),
}));

// Results:
// [
// { name: "Alice", score: 95, rank: "1st" },
// { name: "Charlie", score: 91, rank: "2nd" },
// { name: "Bob", score: 87, rank: "3rd" }
// ]

Error Handling

All number utilities in this module are designed to be safe and handle edge cases gracefully:

  • Null/Undefined Values: Return 0 or appropriate defaults
  • Invalid Numbers: Return 0 instead of NaN
  • Type Safety: Accept various input types and convert safely
  • Negative Numbers: Handle appropriately based on function context

Performance Considerations

  • getTotalAmount: O(n) complexity - iterates through array once
  • checkIfNumber: O(1) - single type check and validation
  • toNumber: O(1) - single conversion operation
  • getOrdinal: O(1) - simple string manipulation


TypeScript Definitions

export function getTotalAmount(item?: any[], key: string): number;
export function checkIfNumber(value: any): number;
export const toNumber: (val: any) => number;
export const getOrdinal: (n: number) => string;