# All files / src/NumberInput NumberInput.utils.ts

98.05% Statements 352/359
96.55% Branches 252/261
100% Functions 30/30
98.48% Lines 324/329

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
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765
    766
    767
    768
    769
    770
    771
    772
    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    787
    788
    789
    790
    791
    792
    793
    794
    795
    796
    797
    798
    799
    800
    801
    802
    803
    804
    805
    806
    807
    808
    809
    810
    811
    812
    813
    814
    815
    816
    817
    818
    819
    820
    821
    822
    823
    824
    825
    826
    827
    828
    829
    830
    831
    832
    8339x
    9x

    9x
    9x
    9x
    9x
    9x
    9x
    9x
    9x
    9x
    9x
    9x
    9x
    9x
    9x
    9x
    9x
    9x
    9x
    9x

    9x
    13x

    13x

    11x

    9x
    289x
    289x

    9x
    774x
    774x

    774x

    9x
    2555x

    2555x
    2555x

    2555x

    2555x

    2555x

    9x
    60x
    34x

    26x
    1x

    25x
    1x

    1x

    24x
    1x

    1x

    23x

    9x

    1083x

    985x

    985x

    985x

    985x

    985x

    985x
    106x

    985x
    985x

    985x

    9x
    610x
    610x
    610x
    610x

    610x

    610x

    9x

    598x
    598x
    892x

    598x

    598x

    598x

    598x

    598x

    598x

    585x

    585x

    576x

    576x

    130x

    598x
    598x
    598x

    598x
    598x

    598x

    598x

    598x

    598x
    598x

    598x

    598x

    598x

    598x

    9x

    568x

    289x

    289x

    289x

    289x
    289x

    289x

    289x

    289x

    289x

    289x
    289x

    289x

    289x

    289x

    185x

    185x

    179x

    179x

    177x

    177x
    3x

    174x

    174x
    18x

    18x

    9x

    18x

    156x
    78x

    78x
    45x

    45x

    45x

    33x
    33x

    33x

    33x
    33x

    33x

    33x

    9x

    16x

    5x

    4x
    4x

    7x

    4x

    2x

    1x

    1x

    9x

    543x

    181x
    181x

    181x

    181x
    181x

    181x

    181x
    181x

    181x

    9x

    18x
    18x
    18x
    18x

    18x
    8x

    4x
    4x
    2x
    2x

    2x

    4x

    4x

    24x

    14x
    1x

    13x

    9x

    147x

    147x
    147x

    147x
    147x
    147x
    147x
    147x
    147x
    147x

    147x
    147x
    147x
    147x
    147x
    147x

    147x

    147x
    147x

    441x

    147x

    147x

    147x

    147x

    147x

    147x

    147x

    147x

    147x

    147x

    147x

    147x

    147x

    147x

    147x

    147x

    147x

    147x

    147x
    34x

    147x
    5x
    5x

    5x
    1x

    4x
    4x

    4x

    44x
    9x

    44x
    4x

    4x

    147x
    10x

    10x
    1x

    9x

    9x

    9x
    9x

    9x
    74x
    12x

    74x
    9x

    9x

    147x
    10x
    20x

    10x

    10x

    10x

    10x

    10x

    147x
    57x

    50x
    50x

    50x
    50x

    50x

    50x

    50x
    50x
    50x
    50x

    50x

    50x

    50x

    50x

    50x

    50x

    50x

    49x

    49x

    49x

    49x

    49x

    49x
    45x
    41x

    37x

    50x
    50x

    50x
    299x

    299x

    299x
    56x

    299x
    49x
    49x

    250x
    1x

    50x

    147x
    147x
    57x

    90x
    3x

    87x
    10x

    77x
    10x

    67x
    5x

    62x
    1x

    61x
    3x

    58x
    27x

    31x
    1x

    30x
    3x

    27x

    147x

    9x
    18x
    18x

    18x

     import { NumberFormatter, NumberOptions } from '@procore/globalization-toolkit'
    import { getFormatterLocale } from '../_utils/i18n'
    import {
      CursorPosition,
      FillDecimalScaleVariant,
      InputValue,
      Locale,
      ParsedInputValue,
      PressedKey,
      Separators,
    } from './NumberInput.types'

    export const defaultLocale = 'en-US'
    export const minus = '-'
    export const emptyString = ''
    export const leftBrace = '('
    export const rightBrace = ')'
    export const backspaceKey = 'Backspace'
    export const deleteKey = 'Delete'
    export const numericKeypadDel = 'Del' // for delete key from numeric keypad in IE
    export const periodKey = '.'
    export const numericKeypadDecimal = 'Decimal' // for period key from numeric keypad in IE
    export const numericKeypadKey = 'Del' // for delete key from numeric keypad in IE
    export const androidUnidentifiedKey = 'Unidentified'
    export const maxDigitLength = 15 // Safe length to avoid the loss of precision
    export const maxDecimalScale = maxDigitLength - 1
    export const commaKey = ','
    export const metaKeyIdentifier = 'Meta'
    export const controlKey = 'Control'
    export const highlightAllKey = 'a'
    export const copyKey = 'c'

    // fixes binary rounding issues (e.g: (0.615).toFixed(2) returns 0.61)
    export function toFixed(value: number, precision: number): number {
      const isExponentialRecord = value.toString().includes('e')

      if (isExponentialRecord) return value

      return Number(
        Number(
          Math.round(Number(value + 'e' + precision)) + 'e-' + precision
        ).toFixed(precision)
      )
    }

    export function formatterFactory(options: NumberOptions): NumberFormatter {
      try {
        return new NumberFormatter(options)
      } catch (error) {
        console.error(
          `Deprecated. @procore/core-react Intl.NumberFormat error for locale ${options.locale}. Will fall back to en-US. In a future major, this will become an error and not provide a fallback.`,
          error
        )
        return new NumberFormatter({ ...options, locale: 'en-US' })
      }
    }

    export function getSeparators(locale: Locale): Separators {
      const formatterLocale = getFormatterLocale(locale as string)
      const separators = new NumberFormatter({
        locale: formatterLocale,
      }).getNumberSeparators()

      return { group: separators.group, decimal: separators.decimal || '' }
    }

    // Check if a valid numeric string is a negative value
    export const isValidNegative = (value: InputValue) => {
      value = String(value)

      const minusRegExp = new RegExp(`${minus}`, 'g')
      const numberOfMinuses = value.match(minusRegExp)?.length
      const containsValidParenthesis =
        value.indexOf(leftBrace) === 0 &&
        value.indexOf(rightBrace) === value.length - 1
      const isNegative =
        (numberOfMinuses === 1 && !containsValidParenthesis) ||
        (!numberOfMinuses && containsValidParenthesis)
      return isNegative
    }

    export function verifyDecimalScale(decimalScale: boolean | number): number {
      if (decimalScale === true) {
        return maxDecimalScale
      }
      if (decimalScale === false) {
        return 0
      }
      if (decimalScale < 0) {
        console.warn(
          `WARNING: Decimal scale (${decimalScale}) is out of range. It was reset to 0. Possible values are from 0 to ${maxDecimalScale}.`
        )
        return 0
      }
      if (decimalScale > maxDecimalScale) {
        console.warn(
          `WARNING: Decimal scale (${decimalScale}) is out of range. It was reset to the max value of ${maxDecimalScale}. Possible values are from 0 to ${maxDecimalScale}.`
        )
        return maxDecimalScale
      }
      return decimalScale
    }

    export function unformat(
      locale: Locale,
      value: InputValue,
      isNumericString = false
    ): ParsedInputValue {
      const isValueNegative = isValidNegative(value)
      const decimal =
        isNumericString || typeof value === 'number'
          ? periodKey
          : getSeparators(locale).decimal
      const numericRegExp = new RegExp(`[^0-9${decimal}]`, 'g')

      let strValue = String(value)

      // Normalize value with numeric characters
      strValue = strValue.replace(numericRegExp, emptyString)

      // Normalize "minus" sign for negatives
      if (isValueNegative) {
        strValue = `${minus}${strValue}`
      }

      // Normalize integer and fraction parts of the value
      const [integer, ...fractions] = strValue.split(decimal)
      const fraction = fractions.join(emptyString)

      return {
        integer,
        decimal: strValue.includes(decimal) ? decimal : emptyString,
        fraction,
        parsedNumber: parseFloat(`${integer}${periodKey}${fraction}`),
      }
    }

    export function refineIntegerFromLeadingZeroes(integer: string) {
      const isNegativeValue = isValidNegative(integer)
      const refinedFromMinus = integer.replace(minus, emptyString)
      const hasLeadingZeroes = refinedFromMinus.slice(0, 1)
      const refinedFromLeadingZeroes = refinedFromMinus.replace(/^0+/, emptyString)
      const zeroPadded =
        hasLeadingZeroes && refinedFromLeadingZeroes === emptyString

      return `${isNegativeValue ? minus : emptyString}${
        zeroPadded ? 0 : refinedFromLeadingZeroes
      }`
    }

    export function getLengthInfo(
      locale: Locale,
      value: InputValue,
      IdecimalScale: number = 0,
      IfillDecimalScale: FillDecimalScaleVariant = 'none',
      isNumericString = false
    ) {
      const isNegativeValue = isValidNegative(value)

      const { integer, decimal, fraction } = unformat(
        locale,
        value,
        isNumericString
      )

      const integerRefinedFromLeadingZeros = refineIntegerFromLeadingZeroes(integer)

      const getIntegerLength = () => {
        const accountEmptyInteger =
          integer === emptyString && decimal && fraction.length > 0

        if (accountEmptyInteger) return 1

        const accountEmptyNegativeInteger =
          integer === minus && decimal && fraction.length > 0

        if (accountEmptyNegativeInteger) return 2

        const accountInteger =
          integer.length > 0 && integer !== emptyString && integer !== minus

        if (accountInteger) return integerRefinedFromLeadingZeros.length

        return 0
      }

      const integerLength = getIntegerLength()
      const fractionLength = fraction.length
      const length = integerLength + fractionLength

      const safeLength = maxDigitLength + (isNegativeValue ? 1 : 0)
      const isSafeLength = safeLength - length > -1

      const isDecimalScaleNonFillable = fillDecimalScale === 'none'

      const safeIntegerLength = isDecimalScaleNonFillable
        ? safeLength
        : safeLength - decimalScale
      const safeFractionLength = isDecimalScaleNonFillable
        ? Math.min(
            safeLength -
              integerRefinedFromLeadingZeros.slice(0, safeIntegerLength).length,
            decimalScale
          )
        : decimalScale

      const isSafeIntegerLength = safeIntegerLength - integerLength > -1
      const isSafeFractionLength = safeFractionLength - fractionLength > -1

      const safelyTruncatedInteger = isSafeIntegerLength
        ? integerRefinedFromLeadingZeros
        : integerRefinedFromLeadingZeros.slice(0, safeIntegerLength)
      const safelyTruncatedFraction = isSafeFractionLength
        ? fraction
        : fraction.slice(0, safeFractionLength)

      const safelyTruncatedValue = `${safelyTruncatedInteger}${decimal}${safelyTruncatedFraction}`

      return {
        length,
        safeLength,
        isSafeLength,
        safelyTruncatedValue,
        integerLength,
        safeIntegerLength,
        isSafeIntegerLength,
        fractionLength,
        safeFractionLength,
        isSafeFractionLength,
      }
    }

    export function format(
      locale: Locale,
      decimalScale: number,
      fillDecimalScale: FillDecimalScaleVariant,
      value: InputValue,
      isNumericString = false
    ): string {
      const fixedDecimalScale = fillDecimalScale === 'always'

      const fillDecimalScaleOnBlur = fillDecimalScale === 'onBlur'

      const autoFilledScale = fixedDecimalScale || fillDecimalScaleOnBlur

      const { length, safeLength, isSafeLength, safelyTruncatedValue } =
        getLengthInfo(
          locale,
          value,
          decimalScale,
          fillDecimalScale,
          isNumericString
        )

      const isTruncatedBeforeFormatting = autoFilledScale || !isSafeLength

      const valueOfVerifiedLength = isTruncatedBeforeFormatting
        ? safelyTruncatedValue
        : value

      const { integer, decimal, fraction } = unformat(
        locale,
        valueOfVerifiedLength,
        isNumericString || typeof value === 'number'
      )

      const options = {
        minimumFractionDigits: fixedDecimalScale
          ? decimalScale
          : Math.min(Math.max(0, fraction?.length || 0), decimalScale),
        maximumFractionDigits: decimalScale,
      }

      const formatterLocale = getFormatterLocale(locale as string)
      const formatter = formatterFactory({ locale: formatterLocale, ...options })

      const isDecimalAllowed = decimalScale > 0

      const isEmptyValue = integer === emptyString && !decimal && !fraction

      if (isEmptyValue) return emptyString

      const isMinusValue = integer === minus && !decimal && !fraction

      if (isMinusValue) return minus

      const isDecimalValue =
        integer === emptyString && decimal && !fraction && !fixedDecimalScale

      if (isDecimalValue) return isDecimalAllowed ? decimal : emptyString

      const isMinusDecimalValue =
        integer === minus && decimal && !fraction && !fixedDecimalScale

      if (isMinusDecimalValue)
        return `${minus}${isDecimalAllowed ? decimal : emptyString}`

      const isFractionValueWithEmptyInteger =
        (integer === minus || integer === emptyString) &&
        decimal &&
        (fraction || (!fraction && fixedDecimalScale))

      if (isFractionValueWithEmptyInteger) {
        const numberOfZerosToPad = decimalScale - fraction.length

        const preparedFraction =
          numberOfZerosToPad > 0 && fixedDecimalScale
            ? fraction.concat(
                Array.from({ length: numberOfZerosToPad }, (_) => '0').join(
                  emptyString
                )
              )
            : fraction.slice(0, decimalScale)

        return `${integer}${
          isDecimalAllowed ? decimal : emptyString
        }${preparedFraction}`
      }

      if (typeof valueOfVerifiedLength === 'number') {
        return formatter.formatNumber(valueOfVerifiedLength)
      }

      if (fraction) {
        const number = parseFloat(
          `${integer}${periodKey}${fraction.slice(
            0,
            options.maximumFractionDigits
          )}`
        )

        Iif (isNaN(number)) return emptyString

        return formatter.formatNumber(number)
      }

      if (integer) {
        const number = parseInt(integer, 10)

        Iif (isNaN(number)) return emptyString

        const formatted = formatter.formatNumber(number)
        const isDecimalAllowed = !(
          options.minimumFractionDigits === 0 && options.maximumFractionDigits === 0
        )
        const isDecimalAvailable =
          decimal && !formatted.includes(decimal) && length < safeLength

        return isDecimalAllowed && isDecimalAvailable
          ? `${formatted}${decimal}`
          : formatted
      }

      return emptyString
    }

    export function identifyPressedKey(
      decimalSeparatorKey: string,
      inputType: string,
      pressedKey: PressedKey,
      prevValue: string,
      value: string
    ) {
      if (pressedKey !== androidUnidentifiedKey) return pressedKey

      if (inputType === 'deleteContentBackward') return backspaceKey

      if (inputType === 'insertText') {
        const diff = value
          .split(emptyString)
          .find(
            (char: string, i: number) => char !== prevValue.split(emptyString)[i]
          )

        switch (diff) {
          case decimalSeparatorKey:
            return decimalSeparatorKey
          case minus:
            return minus
          default:
            return pressedKey
        }
      }

      return pressedKey
    }

    export function getPressedKeyInfo(
      decimalSeparatorKey: string,
      group: string,
      pressedKey: PressedKey,
      prevCursorPosition: CursorPosition,
      prevValue: string,
      verifiedDecimalScale: number
    ) {
      const { selectionStart, selectionEnd, selection } = prevCursorPosition

      const backspaceWasPressed = pressedKey === backspaceKey
      const backspacedChar = backspaceWasPressed
        ? prevValue.slice(selectionStart + (selection ? 0 : -1), selectionEnd)
        : null
      const decimalWasPressed = [
        decimalSeparatorKey,
        numericKeypadDecimal,
      ].includes(pressedKey as string)
      const decimalPressedForInteger =
        decimalWasPressed && verifiedDecimalScale === 0
      const deleteWasPressed = [deleteKey, numericKeypadDel].includes(
        pressedKey as string
      )
      const deletedChar = deleteWasPressed
        ? prevValue.slice(selectionStart, selectionEnd + (selection ? 0 : 1))
        : null

      const thousandsSeparatorWasBackspaced =
        backspaceWasPressed && backspacedChar === group
      const thousandsSeparatorWasDeleted = deleteWasPressed && deletedChar === group

      return {
        backspaceWasPressed,
        backspacedChar,
        decimalWasPressed,
        decimalPressedForInteger,
        deleteWasPressed,
        deletedChar,
        thousandsSeparatorWasBackspaced,
        thousandsSeparatorWasDeleted,
      }
    }

    export function prepareValueToFormatting(
      decimal: string,
      decimalSeparatorKey: string,
      group: string,
      pressedKey: PressedKey,
      prevCursorPosition: CursorPosition,
      prevValue: string,
      verifiedDecimalScale: number,
      value: string
    ) {
      const {
        decimalPressedForInteger,
        thousandsSeparatorWasBackspaced,
        thousandsSeparatorWasDeleted,
      } = getPressedKeyInfo(
        decimalSeparatorKey,
        group,
        pressedKey,
        prevCursorPosition,
        prevValue,
        verifiedDecimalScale
      )

      // Remove preceding/following integer digit instead of thousands separator
      if (thousandsSeparatorWasBackspaced || thousandsSeparatorWasDeleted) {
        const { selectionEnd, selection } = prevCursorPosition

        const getCursorShift = () => {
          if (thousandsSeparatorWasDeleted) {
            const deletedAsSelection = selection === group
            return deletedAsSelection ? 0 : 1
          }
          if (thousandsSeparatorWasBackspaced) return -2
          return 0
        }

        const indexOfIntegerDigitToRemove = selectionEnd + getCursorShift()

        return prevValue
          .split(emptyString)
          .filter((_, i) => i !== indexOfIntegerDigitToRemove)
          .join(emptyString)
      }

      // Ignore typing decimal separator for integer
      if (decimalPressedForInteger) {
        return value.replace(new RegExp(`[${decimal}]`, 'g'), emptyString)
      }

      return value
    }

    export function getNewCursorPosition(
      decimal: string,
      decimalSeparatorKey: string,
      group: string,
      newValue: string,
      pressedKey: PressedKey,
      prevCursorPosition: CursorPosition,
      prevValue: string,
      value: string,
      verifiedDecimalScale: number,
      locale: Locale,
      fillDecimalScale: FillDecimalScaleVariant
    ) {
      const fixedDecimalScale = fillDecimalScale === 'always'

      const { length: prevLength, fractionLength: prevFractionLength } =
        getLengthInfo(locale, prevValue, verifiedDecimalScale, fillDecimalScale)

      const {
        length: newLength,
        safeLength: newSafeLength,
        integerLength: newIntegerLength,
        safeIntegerLength: newSafeIntegerLength,
        fractionLength: newFractionLength,
        safeFractionLength: newSafeFractionLength,
      } = getLengthInfo(locale, newValue, verifiedDecimalScale, fillDecimalScale)

      const {
        backspaceWasPressed,
        backspacedChar,
        decimalWasPressed,
        deleteWasPressed,
        thousandsSeparatorWasBackspaced,
      } = getPressedKeyInfo(
        decimalSeparatorKey,
        group,
        pressedKey,
        prevCursorPosition,
        prevValue,
        verifiedDecimalScale
      )

      const digitTyped = pressedKey && /\d/g.test(pressedKey)
      const digitBackspaced =
        backspaceWasPressed && backspacedChar && /\d/g.test(backspacedChar)
      const decimalBackspaced = backspaceWasPressed && backspacedChar === decimal

      const { selectionStart, selectionEnd, selection } = prevCursorPosition

      const defaultPosition = Math.max(
        selectionEnd + (newValue.length - prevValue.length),
        0
      )

      const isPrevValueNegative = isValidNegative(prevValue)

      const isNewValueNegative = isValidNegative(newValue)

      const isDecimalAllowed = verifiedDecimalScale > 0

      const digitTypedBeforeMinus =
        isPrevValueNegative && selectionEnd === 0 && digitTyped

      const leadingZeroAdded =
        pressedKey === '0' && selectionEnd === (isPrevValueNegative ? 1 : 0)

      const prevIndexOfDecimalSeparator = prevValue.indexOf(decimal)
      const prevCursorPositionInDecimalArea =
        prevIndexOfDecimalSeparator > -1 &&
        prevIndexOfDecimalSeparator < selectionEnd
      const prevCursorPositionInIntegerArea =
        prevIndexOfDecimalSeparator === -1 ||
        prevIndexOfDecimalSeparator >= selectionEnd

      const filledIntegerScaleDigitWasChanged =
        digitTyped &&
        prevCursorPositionInIntegerArea &&
        selectionEnd !== prevValue.length &&
        newLength === prevLength &&
        (newLength === newSafeLength || newIntegerLength === newSafeIntegerLength)

      const isDecimalScaleFilled =
        isDecimalAllowed &&
        newFractionLength === prevFractionLength &&
        newFractionLength === newSafeFractionLength

      const filledDecimalScaleDigitWasBackspaced =
        isDecimalScaleFilled && prevCursorPositionInDecimalArea && digitBackspaced

      const filledDecimalScaleDigitWasChanged =
        isDecimalScaleFilled && prevCursorPositionInDecimalArea && digitTyped

      // Manage cursor when decimalSeparator typed in a new place of a decimal-allowed number
      const decimalNewPosition = newValue.indexOf(decimal)
      const restructuredByDecimal =
        isDecimalAllowed && decimalWasPressed && decimalNewPosition > -1

      // Preserve cursor after first typed digit and before decimal separator
      const fixedDecimalScaleFirstTyping =
        fixedDecimalScale &&
        value.length === (isNewValueNegative ? 2 : 1) &&
        newValue.charAt(isNewValueNegative ? 1 : 0) === pressedKey

      // Preserve cursor before "negative" sign
      const isLeadingZerosRemovedOnPrecedingDigitBackspace =
        backspaceWasPressed &&
        defaultPosition === 0 &&
        selectionEnd - defaultPosition > 1
      const keepCursorBeforeNegativeSign =
        isNewValueNegative && isLeadingZerosRemovedOnPrecedingDigitBackspace

      const getPositionOnRestructuringByDecimal = () => {
        return prevCursorPositionInDecimalArea
          ? newValue.length
          : decimalNewPosition + 1
      }

      const getPositionOnDecimalBackspace = () => {
        const removedCharShift = 1
        const valueLength = newValue.length

        if (prevFractionLength === 0) {
          return valueLength
        }

        let delta = 0
        let anchorDigitIndexFromTheEnd = 0

        newValue
          .split(emptyString)
          .reverse()
          .forEach((char, i) => {
            if (char === group) {
              delta++
            }
            if (i - delta === prevFractionLength - 1) {
              anchorDigitIndexFromTheEnd = i
            }
          })

        return valueLength - removedCharShift - anchorDigitIndexFromTheEnd
      }

      const getPositionOnDelete = () => {
        const firstSymbolDeleted = selectionEnd === 0

        if (firstSymbolDeleted) {
          return 0
        }

        const removedCharShift = 1
        const anchorDigitIndex =
          prevValue
            .slice(0, selectionEnd)
            .replace(new RegExp(`[${group}]`, 'g'), emptyString).length - 1

        let delta = 0
        let cursorPosition = 0

        newValue.split(emptyString).forEach((char, i) => {
          if (char === group) {
            delta++
          }
          if (i - delta === anchorDigitIndex) {
            cursorPosition = i
          }
        })

        return cursorPosition + removedCharShift
      }

      const getPositionOnFilledIntegerScaleDigitChange = () => {
        const getGroupsNumber = (value: string, start?: number, end?: number) => {
          return (
            value.slice(start, end).match(new RegExp(`[${group}]`, 'g'))?.length ||
            0
          )
        }

        const numberOfGroupsBeforeCursorPrevValue = getGroupsNumber(
          prevValue,
          0,
          selectionEnd
        )
        const numberOfGroupsBeforeCursorNewValue = getGroupsNumber(
          newValue,
          0,
          selectionEnd + 1
        )
        const groupsDiffBeforeCursor =
          numberOfGroupsBeforeCursorNewValue - numberOfGroupsBeforeCursorPrevValue

        const typedDigitShift = leadingZeroAdded ? 0 : 1

        return selectionEnd + groupsDiffBeforeCursor + typedDigitShift
      }

      const getPositionOnSelectionChange = () => {
        if (restructuredByDecimal) return getPositionOnRestructuringByDecimal()

        const getPasteText = () => {
          const beforeSelectionPartLength = prevValue.slice(
            0,
            selectionStart
          ).length
          const afterSelectionPartLength = prevValue.slice(selectionEnd).length
          const valueWithoutBeforePart = value.slice(beforeSelectionPartLength)

          const pasteText = valueWithoutBeforePart.slice(
            0,
            valueWithoutBeforePart.length - afterSelectionPartLength
          )

          return pasteText
        }

        const {
          integer: pasteInteger,
          decimal: pasteDecimal,
          fraction: pasteFraction,
        } = unformat(locale, getPasteText())

        const refinedPasteText = `${
          selectionStart === 0
            ? refineIntegerFromLeadingZeroes(pasteInteger)
            : pasteInteger
        }${pasteDecimal}${pasteFraction}`

        const refinedPasteTextLength = refinedPasteText.length

        const anchorDigitIndexRaw =
          prevValue
            .slice(0, selectionStart)
            .replace(new RegExp(`[${group}${decimal}]`, 'g'), emptyString).length -
          1

        const anchorDigitIndexBase =
          anchorDigitIndexRaw > -1 ? anchorDigitIndexRaw : 0

        const anchorDigitIndexShift =
          anchorDigitIndexRaw > -1
            ? refinedPasteTextLength
            : Math.max(refinedPasteTextLength - 1, 0)

        const anchorIndex = anchorDigitIndexBase + anchorDigitIndexShift

        const getCursorPositionShift = () => {
          const negativeToPositiveConversion =
            isValidNegative(refinedPasteText) && isPrevValueNegative

          const integerZeroBasedSelectionRemoval =
            refinedPasteTextLength === 0 && selectionStart === 0

          const integerPartRemoved =
            integerZeroBasedSelectionRemoval &&
            selectionEnd === prevIndexOfDecimalSeparator

          const fractionZeroBasedSelectionRemoval =
            (refinedPasteTextLength === 0 || refinedPasteText === minus) &&
            selectionStart === prevIndexOfDecimalSeparator + 1

          const groupSelectionBackspaced =
            selection === group && thousandsSeparatorWasBackspaced

          if (negativeToPositiveConversion || integerPartRemoved) return -1
          if (integerZeroBasedSelectionRemoval || groupSelectionBackspaced) return 0
          if (fractionZeroBasedSelectionRemoval) return 2

          return 1
        }

        let delta = 0
        let cursorPosition = 0

        for (let i = 0; i < newValue.length; i++) {
          const char = newValue.charAt(i)

          const isDeltaIncrementer =
            char === group || (char === decimal && !pasteDecimal)

          if (isDeltaIncrementer) {
            delta++
          }

          if (i - delta === anchorIndex) {
            cursorPosition = i + getCursorPositionShift()
            break
          }

          if (i + 1 === newValue.length) {
            cursorPosition = newValue.length
          }
        }

        return cursorPosition
      }

      const getNewPosition = () => {
        if (selection) {
          return getPositionOnSelectionChange()
        }

        if (digitTypedBeforeMinus) {
          return 2
        }

        if (filledIntegerScaleDigitWasChanged) {
          return getPositionOnFilledIntegerScaleDigitChange()
        }

        if (deleteWasPressed) {
          return getPositionOnDelete()
        }

        if (decimalBackspaced) {
          return getPositionOnDecimalBackspace()
        }

        if (filledDecimalScaleDigitWasBackspaced) {
          return selectionEnd - 1
        }

        if (filledDecimalScaleDigitWasChanged) {
          return selectionEnd + 1
        }

        if (restructuredByDecimal) {
          return getPositionOnRestructuringByDecimal()
        }

        if (fixedDecimalScaleFirstTyping) {
          return isNewValueNegative ? 2 : 1
        }

        if (keepCursorBeforeNegativeSign) {
          return 1
        }

        return defaultPosition
      }

      return getNewPosition()
    }

    export function identicalLocales(one: Locale, two: Locale) {
      const array1 = Array.isArray(one) ? one : [one]
      const array2 = Array.isArray(two) ? two : [two]

      return array1.join() === array2.join()
    }