forked from handsontable/hyperformula
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumberLiteralHelper.ts
40 lines (34 loc) · 1.3 KB
/
NumberLiteralHelper.ts
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
/**
* @license
* Copyright (c) 2021 Handsoncode. All rights reserved.
*/
import {Config} from './Config'
import {Maybe} from './Maybe'
export class NumberLiteralHelper {
private readonly numberPattern: RegExp
private readonly allThousandSeparatorsRegex: RegExp
constructor(
private readonly config: Config
) {
const thousandSeparator = this.config.thousandSeparator === '.' ? `\\${this.config.thousandSeparator}` : this.config.thousandSeparator
const decimalSeparator = this.config.decimalSeparator === '.' ? `\\${this.config.decimalSeparator}` : this.config.decimalSeparator
this.numberPattern = new RegExp(`^([+-]?((${decimalSeparator}\\d+)|(\\d+(${thousandSeparator}\\d{3,})*(${decimalSeparator}\\d*)?)))(e[+-]?\\d+)?$`)
this.allThousandSeparatorsRegex = new RegExp(`${thousandSeparator}`, 'g')
}
public numericStringToMaybeNumber(input: string): Maybe<number> {
if (this.numberPattern.test(input)) {
const num = this.numericStringToNumber(input)
if (isNaN(num)) {
return undefined
}
return num
}
return undefined
}
public numericStringToNumber(input: string): number {
const normalized = input
.replace(this.allThousandSeparatorsRegex, '')
.replace(this.config.decimalSeparator, '.')
return Number(normalized)
}
}