"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getCleanDecimalWithLimits = exports.cleanDecimalInput = exports.ensureDecimals = exports.roundToPrecision = exports.roundToDecimal = exports.getNumberOfDecimals = void 0;

var _is = require("./is");

const getNumberOfDecimals = num => {
  const postDecimalString = (num + '').split('.')[1];
  return postDecimalString ? postDecimalString.length : 0;
};

exports.getNumberOfDecimals = getNumberOfDecimals;

const roundToDecimal = (number, precision) => {
  const factor = Math.pow(10, precision);
  return Math.round(number * factor) / factor;
};

exports.roundToDecimal = roundToDecimal;

const roundToPrecision = (number, precision) => {
  if (!number || isNaN(number)) {
    return 0;
  }

  const decimalString = roundToDecimal(number, precision).toString();
  const numberOfDigitsBeforePeriod = decimalString.split('.')[0].length;
  const actualPrecision = Math.max(precision - numberOfDigitsBeforePeriod, 0);
  return roundToDecimal(number, actualPrecision);
};

exports.roundToPrecision = roundToPrecision;

const ensureDecimals = (number, targetDecimals = 0) => {
  const numberOfDecimals = getNumberOfDecimals(number);
  let numberToAdd = targetDecimals - numberOfDecimals;

  if (!numberToAdd) {
    return number;
  }

  let result = number + (numberOfDecimals === 0 ? '.' : '');

  while (numberToAdd--) {
    result += '0';
  }

  return result;
};

exports.ensureDecimals = ensureDecimals;
const floatInputRE = /[^0-9.]/g;
const leadingZerosWithDecimalRE = /^0{2,}\./g;
const leadingZerosNoDecimalRE = /^0{1,}[0-9]/g;
const periodRE = /\./g;

const cleanDecimalInput = str => {
  let matches = 0;

  if ((0, _is.isNumber)(str)) {
    str = str.toString();
  }

  return str // removes invalid characters anywhere
  .replace(floatInputRE, '') // removes leading zeros if there's more than one before a decimal '00.123'
  .replace(leadingZerosWithDecimalRE, '0.') // removes leading zeros if there's no decimal
  .replace(leadingZerosNoDecimalRE, match => match.slice(-1)) // removes all but first decimal
  .replace(periodRE, () => matches++ > 0 ? '' : '.');
};

exports.cleanDecimalInput = cleanDecimalInput;

const getCleanDecimalWithLimits = ({
  maxLenBefore,
  maxLenAfter
}) => str => {
  const cleaned = cleanDecimalInput(str);
  let split = cleaned.split('.');
  let [before, after] = split;

  if (!before && !after) {
    return cleaned;
  }

  if ((0, _is.isNumber)(maxLenBefore) && before) {
    before = before.slice(0, maxLenBefore);
  }

  if ((0, _is.isNumber)(maxLenAfter) && after) {
    after = after.slice(0, maxLenAfter);
  }

  if (!before) {
    return ".".concat(after);
  }

  if (after === undefined) {
    return before;
  }

  return [before, after].join('.');
};

exports.getCleanDecimalWithLimits = getCleanDecimalWithLimits;