import { formatCurrency } from "@angular/common";

export class NumberUtils {

    public static Ordinal(value: number): string {
        let suffix = '';
        const last = value % 10;
        const specialLast = value % 100;
        if (!value || value < 1) {
            return value.toString();
        }
        if (last === 1 && specialLast !== 11) {
            suffix = 'st';
        } else if (last === 2 && specialLast !== 12) {
            suffix = 'nd';
        } else if (last === 3 && specialLast !== 13) {
            suffix = 'rd';
        } else {
            suffix = 'th';
        }
        return value + suffix;
    }

    public static Clamp(n: number, min: number, max: number): number {
        return Math.min(max, Math.max(min, n));
    }

    public static SortFunction(a: number, b: number): number {
        return a - b;
    }

    public static Sum(array: number[], key: any = undefined): number {
        if (key) {
            return array.reduce((a, b) => (isNaN(a[key]) ? 0 : a[key]) + (isNaN(b[key]) ? 0 : b[key]), 0);
        }
        return array.reduce((a, b) => (isNaN(a) ? 0 : a) + (isNaN(b) ? 0 : b), 0);
    }

    public static FormatCurrency(v: number, zeroExpression: string = '0'): string {
        return ['', 0, null, undefined, NaN].includes(v) ? zeroExpression : formatCurrency(v, "en", "", "", `0.2`);
    }
    public static FormatNumber(v: number, precision: number = 0, zeroExpression: string = '0'): string {
        return ['', 0, null, undefined, NaN].includes(v) ? zeroExpression : formatCurrency(v, "en", "", "", `0.${precision}`);
    }
}