-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
MoneyRequestUtils.ts
74 lines (64 loc) · 2.19 KB
/
MoneyRequestUtils.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
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
import {ValueOf} from 'type-fest';
import CONST from '../CONST';
/**
* Strip comma from the amount
*/
function stripCommaFromAmount(amount: string): string {
return amount.replace(/,/g, '');
}
/**
* Strip spaces from the amount
*/
function stripSpacesFromAmount(amount: string): string {
return amount.replace(/\s+/g, '');
}
/**
* Adds a leading zero to the amount if user entered just the decimal separator
*
* @param amount - Changed amount from user input
*/
function addLeadingZero(amount: string): string {
return amount === '.' ? '0.' : amount;
}
/**
* Calculate the length of the amount with leading zeroes
*/
function calculateAmountLength(amount: string): number {
const leadingZeroes = amount.match(/^0+/);
const leadingZeroesLength = leadingZeroes?.[0]?.length ?? 0;
const absAmount = parseFloat((Number(stripCommaFromAmount(amount)) * 100).toFixed(2)).toString();
if (/\D/.test(absAmount)) {
return CONST.IOU.AMOUNT_MAX_LENGTH + 1;
}
return leadingZeroesLength + (absAmount === '0' ? 2 : absAmount.length);
}
/**
* Check if amount is a decimal up to 3 digits
*/
function validateAmount(amount: string): boolean {
const decimalNumberRegex = new RegExp(/^\d+(,\d+)*(\.\d{0,2})?$/, 'i');
return amount === '' || (decimalNumberRegex.test(amount) && calculateAmountLength(amount) <= CONST.IOU.AMOUNT_MAX_LENGTH);
}
/**
* Replaces each character by calling `convertFn`. If `convertFn` throws an error, then
* the original character will be preserved.
*/
function replaceAllDigits(text: string, convertFn: (char: string) => string): string {
return text
.split('')
.map((char) => {
try {
return convertFn(char);
} catch {
return char;
}
})
.join('');
}
/**
* Check if distance request or not
*/
function isDistanceRequest(iouType: ValueOf<typeof CONST.IOU.MONEY_REQUEST_TYPE>, selectedTab: ValueOf<typeof CONST.TAB>): boolean {
return iouType === CONST.IOU.MONEY_REQUEST_TYPE.REQUEST && selectedTab === CONST.TAB.DISTANCE;
}
export {stripCommaFromAmount, stripSpacesFromAmount, addLeadingZero, validateAmount, replaceAllDigits, isDistanceRequest};