Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 | 562x 15x 15x 562x 562x 562x 130x 113x 562x 562x 562x 562x 562x 562x 91x 91x 562x 562x 562x 562x 562x 562x 116x 562x 562x 562x 12x 562x 576x 576x 4032x 562x 562x 562x 3x 562x 170x 170x 170x 170x 170x 170x 112x 10x 102x 32x 70x 32x 38x 170x 281x 281x 281x 281x 281x 2x 279x 195x 84x 84x 84x 562x 40x 40x 6x 562x 562x 833x 833x 2071x 619x 1452x 1452x 94x 98x 94x 562x 562x 562x 12x 12x 12x 562x 502x 20807x 20515x 20495x 20495x 1669x 18826x 18826x 562x 1191x 562x 1x 562x 10x 562x 369x 369x 16x 353x 353x 353x 353x 353x 369x 562x 2152x 562x 2243x 2243x 2243x 2243x 2243x 2243x 2243x 562x 562x 261x 261x 261x 253x 8x 562x 562x 562x 1475x 1349x 1349x 562x 627x 105x 105x 562x 291x 562x 275x 275x 562x 289x 254x 562x 562x 562x 240x 240x 240x 240x 240x 56x 184x 2664x 1670x 1670x 216x 216x 40808x 39155x 685x 685x 685x 38470x 18907x 18907x 18559x 18189x 18189x 18189x 18189x 370x 370x 370x | import { LibraryImage } from "@components/Settings/MediaLibrary/library.types";
import { differenceInHours } from "date-fns";
import moment from "moment";
import { PLATFORM_TIMEZONE } from "@utils/timezones";
import { matchPath } from "react-router-dom";
import { marked } from "marked";
import { isValidHexColor } from "@validation/regex";
export const sanitizePaste = (value: string): string => {
Iif (!value) return "";
return value
.replace(
/[\u200B-\u200D\uFEFF\u200E\u200F\u202A-\u202E\u00AD\u2060-\u2064\u180E]/g,
"",
)
.replace(/\u00A0/g, " ")
.trim();
};
export const MenuUniqueIds = {
paint0: "p_00",
paint1: "p_01",
paint2: "p_02",
paint3: "p_03",
paint4: "p_04",
paint5: "p_05",
paint6: "p_06",
paint7: "p_07",
paint8: "p_08",
paint9: "p_09",
};
export const toDeFormat = (n?: number) => {
if (n === null || n === undefined) return "";
return Number(n).toLocaleString("de-DE", {
maximumFractionDigits: 2,
minimumFractionDigits: 2,
});
};
export const toEnFormat = (n?: number) => {
if (n === null || n === undefined) return "";
return Number(n).toLocaleString("en-EN", {
maximumFractionDigits: 2,
minimumFractionDigits: 2,
});
};
export const toEnFormatWithDecimal = (n?: number | string) => {
if (n === null || n === undefined) return "";
const [wholePart, FraconPart] = `${n}`.split(".");
return [Number(wholePart).toLocaleString("en-US"), FraconPart]
.filter(Boolean)
.join(".");
};
export const truncateString = (str?: string) => {
if (str === null || str === undefined) return "";
return str.length > 14 ? str.substring(0, 15) + "..." : str;
};
export const truncateStringLength = (str: string, limit: number) => {
if (str === null || str === undefined) return "";
return str.length > limit ? str.substring(0, limit) + " ..." : str;
};
export const truncateNumber = (n?: number) => {
if (n === null || n === undefined) return "";
return n.toString().length > 14
? n.toString().substring(0, 15) + "..."
: n.toString();
};
export const getActive = (path: string, pathname: string): boolean => {
return path ? !!matchPath({ path, end: false }, pathname) : false;
};
export const getActiveItem = (path: string, pathname: string): boolean => {
const arr = pathname.split("/");
return arr[arr.length - 1] === path.trim();
};
export const getComponentActive = (component: JSX.Element): boolean => {
return component ? true : false;
};
export const isAllActive = (arr: { [key: string]: boolean }) =>
Object.values(arr).every((v) => v === true);
export const isAllArrayDisabled = (arr: { [key: string]: any[] }) =>
Object.values(arr).every((value) => value.length < 1);
export const convertTimestamp = (timestamp: number): [string, string] => {
const dateObj = new Date(timestamp * 1000);
const dateStr = dateObj.toISOString().substr(0, 10);
const timeStr = dateObj.toTimeString().substr(0, 8);
return [dateStr, timeStr];
};
export const formatDate = (unixTimestamp: number): string => {
if (!Number.isFinite(unixTimestamp)) {
return "";
}
const date = new Date(unixTimestamp * 1000);
const options: Intl.DateTimeFormatOptions = {
month: "long",
day: "numeric",
year: "numeric",
};
const formatter = new Intl.DateTimeFormat("en-US", options);
const formattedDate = formatter.format(date);
const day = date.getDate();
const suffix = getNumberSuffix(day);
const year = date.getFullYear();
return formattedDate.replace(/\d{1,2}/, `$&${suffix}`);
};
export const formatTimestampWithTimezone = (date: number) => {
return moment
.unix(date)
.tz(PLATFORM_TIMEZONE)
.format("MMMM DD, YYYY, hh:mm:ss A z");
};
export const getNumberSuffix = (day: number): string => {
if (day >= 11 && day <= 13) {
return "th";
}
const lastDigit = day % 10;
switch (lastDigit) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
};
export function hexToRgba(hexCode: string, opacity = 1) {
if (!isValidHexColor(hexCode)) {
throw new Error("Bad Hex");
}
let hex = hexCode.replace("#", "");
if (hex.length === 3) {
hex = `${hex[0]}${hex[0]}${hex[1]}${hex[1]}${hex[2]}${hex[2]}`;
}
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
if (opacity < 0 || opacity >= 1) {
opacity = 1;
}
return `rgba(${r},${g},${b},${opacity})`;
}
export const replaceCloudfront = (url: string) => {
if (!url) {
return url;
}
return url.replace(
"https://d3ssfzdknds1vv.cloudfront.net",
"https://staging-givepayments-media-upload.s3.us-west-1.amazonaws.com",
);
};
export const toUTCDateFormat = (date: number) => {
return moment.unix(date).tz(PLATFORM_TIMEZONE).format("MMM D, YYYY, h:mm:ss A z");
};
export const convertImagesForViewer = (
images: LibraryImage[],
size = "original",
) =>
images?.map((image: LibraryImage, index: number) => {
// server is taking some time(around 10-30s) to scale image to small size(so fetching /small or /thumb gives error)
// so for recently uploaded image -> show original one
const isUploadedRecently =
image.createdAt + 30 > new Date().getTime() / 1000;
const urlPostfix = isUploadedRecently ? `/original` : `/${size}`;
return {
id: image.id,
index: index,
src: image.URL + urlPostfix,
alt: image.label,
};
});
export function detectMobile() {
const toMatch = [
/Android/i,
/webOS/i,
/iPhone/i,
/iPad/i,
/iPod/i,
/BlackBerry/i,
/Windows Phone/i,
];
return toMatch.some((toMatchItem) => {
return navigator.userAgent.match(toMatchItem);
});
}
export const isMobile = detectMobile();
type Property<T> = {
[key: string]: T;
};
export const createPropertyOnChange = (
dirtyField: unknown,
key: string,
value: unknown | Property<unknown>,
) => {
if (!dirtyField) {
return {};
}
return { [key]: value };
};
export const progressPercentageValue = (
currentCount: number,
maxCount: number,
): number => {
return Math.round((currentCount * 100) / maxCount);
};
export const formatCardNumber = (cardNumber: string) => {
const cleanedNumber = cardNumber.replace(/\D/g, "");
let formattedNumber = "";
const cardType = getCardType(cleanedNumber);
const currentValue = cleanedNumber;
Iif (cardType === "AMEX") {
formattedNumber = currentValue.replace(
/^(\d{4})(\d{0,7})(\d{0,4}).*$/,
function (_, group1, group2, group3) {
if (group2 === "") {
return currentValue;
} else if (group3 === "") {
return `${group1} ${group2}`;
} else {
return `${group1} ${group2} ${group3}`;
}
},
);
} else {
formattedNumber = currentValue.replace(
/^(\d{4})(\d{0,4})(\d{0,4})(\d{0,4}).*$/,
function (_, group1, group2, group3, group4) {
if (group2 === "") {
return currentValue;
} else if (group3 === "") {
return `${group1} ${group2}`;
} else if (group4 === "") {
return `${group1} ${group2} ${group3}`;
} else {
return `${group1} ${group2} ${group3} ${group4}`;
}
},
);
}
return {
formattedNumber,
cardType,
};
};
export function getCardType(cardNumber: string) {
const amexPattern = /^3[47]/;
const visaPattern = /^4/;
const mastercardPattern =
/^((5[1-5])|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720))/;
const discoverPattern =
/^65[4-9]|64[4-9]|6011|(622(?:12|1[3-9]|[2-8]|9[01]|92[0-5]))/;
if (amexPattern.test(cardNumber)) {
return "AMEX";
} else if (visaPattern.test(cardNumber)) {
return "Visa";
} else Iif (mastercardPattern.test(cardNumber)) {
return "Mastercard";
} else Iif (discoverPattern.test(cardNumber)) {
return "Discover";
} else {
return "Other";
}
}
export const getValueFromString = (value: string) => {
const float = parseFloat(value.replaceAll(",", "")).toFixed(2);
return float;
};
export function convertToString(input: number): string {
return input.toLocaleString("en-US", {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
}
export const sanitizer = (str: string) =>
str === "one_time" ? "One-Time" : capitalizeFirstLetter(str);
export const capitalizeCardType = (str: string) => {
Iif (!str) return "";
// Split by spaces and common punctuation, but preserve the separators
return str
.split(/(\s+|[-,'"])/)
.map((word) => {
// Skip empty strings and separators (spaces, hyphens, commas, apostrophes, quotes)
if (!word || /^\s+$/.test(word) || /^[-,'"]+$/.test(word)) {
return word;
}
// Only force-lowercase words that are entirely uppercase (e.g. "VISA", "SENT").
// Preserve mixed-case words like "GivePayments" to avoid mangling brand names.
const isAllUpperCase = word === word.toUpperCase();
return (
word.charAt(0).toUpperCase() +
(isAllUpperCase ? word.slice(1).toLowerCase() : word.slice(1))
);
})
.join("");
};
export function capitalizeEachWord(str: string, divider = " "): string {
const words = str.split(divider);
const capitalizedWords = words.map((word) => capitalizeFirstLetter(word));
return capitalizedWords.join(divider);
}
export const formatTaxID = (value: string) => {
if (!value) return value;
const currentValue = value.replace(/[^\d]/g, "");
const cvLength = currentValue.length;
if (cvLength < 3) return currentValue;
if (cvLength < 11)
return `${currentValue.slice(0, 2)}-${currentValue.slice(2, 10)}`;
};
export const partiallyMaskString = (
input: string,
visibleCharactersFromStart: number,
visibleCharactersFromEnd: number,
maskCharacter = "*",
): string => {
if (
visibleCharactersFromStart >= input.length ||
visibleCharactersFromEnd >= input.length ||
visibleCharactersFromStart + visibleCharactersFromEnd >= input.length
) {
const vcfs = 2,
vcfe = 2;
const maskedCharacterCount = Math.max(input.length - vcfs - vcfe, 0);
const maskedPart = maskCharacter.repeat(maskedCharacterCount);
return input.slice(0, vcfs) + maskedPart + input.slice(-vcfe);
}
const visiblePartFromStart = input.slice(0, visibleCharactersFromStart);
const visiblePartFromEnd = input.slice(-visibleCharactersFromEnd);
const maskedCharacterCount =
input.length - visibleCharactersFromStart - visibleCharactersFromEnd;
const maskedPart = maskCharacter.repeat(maskedCharacterCount);
return visiblePartFromStart + maskedPart + visiblePartFromEnd;
};
export const formatVariantValue = (value: string | number): number => {
const newValue =
typeof value === "string" ? getValueFromString(value) : value;
const integerValue = `${newValue}`.replace(".", "");
return parseInt(integerValue);
};
export const roundToNearestTenth = (x: number) => {
// round up or down to the nearest tenth the number which decimal part contains hudrends or more
//Example: 1.23 => 1.2; 1.27 => 1.3
return Math.round(x * 10) / 10;
};
export function parseAmount(
amount?: number | null | string,
fractionDigits = 2,
stripDecimals = false,
noFormat = false,
) {
if (amount === null || amount === "") return (0).toFixed(fractionDigits);
if (typeof amount === "string" && isNaN(Number(amount))) return amount;
const num = parseToNumber(amount);
if (noFormat) {
return num?.toLocaleString("en-US", {
minimumFractionDigits: fractionDigits,
maximumFractionDigits: fractionDigits,
});
}
const formatted = formatNumberToShort(num, {
maxFractionDigits: fractionDigits,
});
Eif (!stripDecimals) return formatted;
// Delegate to new formatter
return formatNumberToShort(amount, { maxFractionDigits: fractionDigits });
}
export const parseAmountWithoutDecimals = (amount?: number | null | string) => {
return parseAmount(amount)?.slice(0, -3);
};
export const sleep = (duration: number) =>
new Promise((resolve) => setTimeout(resolve, duration));
export const encodeString = (description: string) =>
btoa(unescape(encodeURIComponent(description)));
export const getSettledPromise = (promise: PromiseSettledResult<any>) => {
return promise?.status === "fulfilled" ? promise?.value : null;
};
export function bytesToSize(bytes: number, decimals = 1) {
let sizeString = "";
if (!Number(bytes)) {
sizeString = "0B";
} else {
const kbToBytes = 1000;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
const index = Math.floor(Math.log(bytes) / Math.log(kbToBytes));
sizeString = `${parseFloat(
(bytes / Math.pow(kbToBytes, index)).toFixed(dm),
)}${sizes[index]}`;
}
return {
sizeString,
};
}
export const formatFromUnixWithFormat = (date: number, format: string) =>
moment(new Date(date * 1000))
.tz(PLATFORM_TIMEZONE)
.format(format);
export const isValidObject = (obj: any) =>
Object.values(obj).every((val) => val);
export function rgbaToHex(rgba: any, ignoreAlpha?: boolean) {
// Extract the individual RGB values and alpha from the RGBA string
const [r, g, b, a] = rgba.match(/\d+(\.\d+)?/g);
// Convert the RGB values to hexadecimal
const rHex = Math.round(parseFloat(r)).toString(16).padStart(2, "0");
const gHex = Math.round(parseFloat(g)).toString(16).padStart(2, "0");
const bHex = Math.round(parseFloat(b)).toString(16).padStart(2, "0");
// Convert alpha to hexadecimal (if needed)
const aHex = a
? Math.round(parseFloat(a) * 255)
.toString(16)
.padStart(2, "0")
: "";
// Construct the hexadecimal color value
const hexColor = ignoreAlpha
? `#${rHex}${gHex}${bHex}`.toUpperCase()
: `#${rHex}${gHex}${bHex}${aHex}`.toUpperCase();
return hexColor;
}
export const getUrlExtension = (url?: string) =>
url?.split(/[#?]/)?.[0]?.split(".")?.pop()?.trim() || "";
export const getSubString = (
startChar: string,
endChar: string,
str: string,
) => {
const startIndex = str?.indexOf(startChar);
const endIndex = endChar
? str?.indexOf(endChar, startIndex + 1)
: str?.length + 1;
if (startIndex !== -1 && endIndex !== -1) {
return str?.substring(startIndex + 1, endIndex);
} else {
return "";
}
};
export const getIndefiniteArticle = (word: string) => {
const vowels = ["a", "e", "i", "o", "u"];
const firstLetter = word?.[0]?.toLowerCase();
return vowels?.includes(firstLetter) ? "an" : "a";
};
export const normalizeBetweenTwoRanges = (
value: number,
oldRange: number[],
newRange: number[],
) => {
const [minOldValue, maxOldValue] = oldRange;
const [minNewValue, maxNewValue] = newRange;
return (
minNewValue +
((value - minOldValue) * (maxNewValue - minNewValue)) /
(maxOldValue - minOldValue)
);
};
export const getNumberFromString = (text: string) => {
const id = text.match(/\d+/);
if (!id?.[0]) return null;
const integer = parseInt(id[0]);
if (Number.isNaN(integer)) return null;
return integer;
};
export function capitalizeFirstLetter(str: string) {
if (!str) return "";
const formattedStr = str.replace(/_/g, " ").toLowerCase();
return formattedStr[0].toUpperCase() + formattedStr.slice(1);
}
export function millisecondsToHHMMSS(
milliseconds: number,
isLongCooldownActive: boolean,
) {
const hours = Math.floor(milliseconds / (60 * 60 * 1000));
const minutes = Math.floor((milliseconds % (60 * 60 * 1000)) / (60 * 1000));
const seconds = Math.floor((milliseconds % (60 * 1000)) / 1000);
if (isLongCooldownActive) {
return [
String(hours).padStart(2, "0"),
String(minutes).padStart(2, "0"),
String(seconds).padStart(2, "0"),
].join(":");
}
return [
String(minutes).padStart(2, "0"),
String(seconds).padStart(2, "0"),
].join(":");
}
export enum TAX_ID_ENUM {
SSN = "ssn",
EIN = "ein",
}
export const getTaxIdFormat = (
taxId?: string,
tinType?: string,
hidePartiallySSN?: boolean,
) => {
if (!taxId) return "";
Iif (tinType === TAX_ID_ENUM.SSN) {
if (hidePartiallySSN) return "•••• " + taxId.slice(-4);
return `${taxId.slice(0, 3)}-${taxId.slice(3, 5)}-${taxId.slice(5)}`;
}
return `${taxId.slice(0, 2)}-${taxId.slice(2)}`;
};
export const formatLargeNumber = (num: any, fractionDigits?: number) => {
return num.toLocaleString("en-US", {
notation: "compact",
minimumFractionDigits: fractionDigits ?? 2,
maximumFractionDigits: fractionDigits ?? 2,
});
};
export const formatCharCountWithLimit = (
inputText: string | undefined,
maxLength: number,
): string => {
const currentLength = inputText?.length || 0;
return `${currentLength}/${maxLength}`;
};
export const isMoreThan24HoursAgo = (timestamp: number | null) => {
if (!timestamp) return false;
return differenceInHours(new Date(), new Date(timestamp * 1000)) > 24;
};
export const isMerchantDisallowedToTransferMoney = (merchantData: any) => {
if (!merchantData) return true;
const {
statusName,
submerchantAllowedToTransfer,
hasApprovedLegalEntity,
riskCriticalAt,
hasApprovedBankAccount,
hasApprovedLinkedBankAccount,
type,
canTransferMoney,
} = merchantData;
const isEnterprise = type === "enterprise";
const isInRiskLevelForMoreThan24Hours = isEnterprise
? false
: isMoreThan24HoursAgo(riskCriticalAt || 0);
return Boolean(
statusName !== "approved" ||
!submerchantAllowedToTransfer ||
!hasApprovedLegalEntity ||
isInRiskLevelForMoreThan24Hours ||
(!hasApprovedBankAccount && !hasApprovedLinkedBankAccount) ||
!canTransferMoney,
);
};
export function getPlusMinusPrefix(value: number): string {
if (value === 0) return "";
return value > 0 ? "+" : "-";
}
export const ALLOWED_TAGS = [
"b",
"i",
"strong",
"em",
"a",
"p",
"br",
"ul",
"li",
];
export const ALLOWED_ATTR = ["title"];
export function convertMarkdown(input: string): string {
const trimmed = input.trim();
// If empty, return empty string
Iif (!trimmed) return "";
// Detect if input has markdown syntax
// eslint-disable-next-line
const markdownIndicators = /[*_`#>\[\]()~\-]/;
const hasMarkdown = markdownIndicators.test(trimmed);
if (hasMarkdown) {
return marked.parse(trimmed, { breaks: true }) as string;
}
// No markdown — convert \n to <br/>
return trimmed.replace(/\n/g, "<br/>");
}
export function safeParse<T = any>(raw: string | undefined | null): T | null {
if (!raw || typeof raw !== "string") return null;
try {
return JSON.parse(raw) as T;
} catch (err) {
console.error("Invalid JSON input:", err);
return null;
}
}
export function parseToNumber(val?: number | string | null): number | null {
if (val === null || val === undefined) return null;
if (typeof val === "string") {
const clean = val.replace(/,/g, "").trim();
const num = Number(clean);
return Number.isFinite(num) ? num : null;
}
return Number.isFinite(val) ? val : null;
}
export function formatNumberToShort(
value?: number | string | null,
{
lowercase = false,
maxFractionDigits = 2,
}: { lowercase?: boolean; maxFractionDigits?: number } = {},
): string {
const num = parseToNumber(value);
if (num === null) return String(value ?? "");
// Only shorten if ≥ 1,000,000
if (Math.abs(num) < 1_000_000) {
// truncate instead of round ( for percentages )
const str = num.toFixed(maxFractionDigits + 1); // Extra digit for precision
const truncatedStr = str.substring(
0,
str.indexOf(".") + 1 + maxFractionDigits,
);
const truncated = parseFloat(truncatedStr);
return truncated.toLocaleString("en-US", {
minimumFractionDigits: maxFractionDigits,
maximumFractionDigits: maxFractionDigits,
});
}
// Use compact format for 1M and above
const formatter = new Intl.NumberFormat("en-US", {
notation: "compact",
minimumFractionDigits: maxFractionDigits,
maximumFractionDigits: maxFractionDigits,
});
const formatted = formatter.format(num);
return lowercase
? formatted.replace(/K|M|B|T/g, (m) => m.toLowerCase())
: formatted;
}
|