import BigNumber from "bignumber.js";

const FORMAT = {
  groupSeparator: " ",
  groupSize: 3,
  decimalSeparator: ".",
};
BigNumber.config({ FORMAT });

export const toSuffixFormat = (num?: any, digits = 2, roundingMode?: BigNumber.RoundingMode): string => {
  const lookup = [
    { value: 1e9, symbol: "B" },
    { value: 1e6, symbol: "M" },
    { value: 1e3, symbol: "k" },
  ];

  if (!num) {
    return num;
  }

  const rx = /\.0+$|(\.[0-9]*[1-9])0+$/;
  const castedNumber = num instanceof BigNumber ? num : new BigNumber(num ?? 0);
  const item = lookup.find(({ value }) => castedNumber.isGreaterThanOrEqualTo(value)) ?? { value: 1, symbol: "" };

  return castedNumber.div(item.value).toFormat(digits, roundingMode).replace(rx, "$1") + item.symbol;
};