Skip to content

Commit

Permalink
fix(kit): maskitoParseNumber cannot parse prefix/postfix with points (
Browse files Browse the repository at this point in the history
  • Loading branch information
nsbarsukov authored Jan 9, 2024
1 parent e434f16 commit ff15578
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
7 changes: 6 additions & 1 deletion projects/kit/src/lib/masks/number/utils/parse-number.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@ export function maskitoParseNumber(
const hasNegativeSign = !!maskedNumber.match(
new RegExp(`^\\D*[${CHAR_MINUS}\\${CHAR_HYPHEN}${CHAR_EN_DASH}${CHAR_EM_DASH}]`),
);
const escapedDecimalSeparator = escapeRegExp(decimalSeparator);

const unmaskedNumber = maskedNumber
.replace(new RegExp(`[^\\d${escapeRegExp(decimalSeparator)}]`, 'g'), '')
// drop all decimal separators not followed by a digit
.replace(new RegExp(`${escapedDecimalSeparator}(?!\\d)`, 'g'), '')
// drop all non-digit characters except decimal separator
.replace(new RegExp(`[^\\d${escapedDecimalSeparator}]`, 'g'), '')
.replace(decimalSeparator, '.');

return unmaskedNumber
Expand Down
32 changes: 32 additions & 0 deletions projects/kit/src/lib/masks/number/utils/tests/parse-number.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,38 @@ describe('maskitoParseNumber', () => {
expect(maskitoParseNumber('>-42')).toBe(-42);
expect(maskitoParseNumber('> -42')).toBe(-42);
});

describe('prefix/postfix includes point and space', () => {
it('parses INTEGER number with postfix " lbs."', () => {
expect(maskitoParseNumber('42 lbs.')).toBe(42);
expect(maskitoParseNumber('1 000 lbs.')).toBe(1000);
expect(maskitoParseNumber('1 000 lbs.')).toBe(1000);
});

it('parses DECIMAL number with postfix " lbs."', () => {
expect(maskitoParseNumber('0.42 lbs.')).toBe(0.42);
expect(maskitoParseNumber('.42 lbs.')).toBe(0.42);
expect(maskitoParseNumber('1 000.42 lbs.')).toBe(1000.42);
expect(maskitoParseNumber('1 000. lbs.')).toBe(1000);
});

it('parses INTEGER number with prefix "lbs. "', () => {
expect(maskitoParseNumber('lbs. 42')).toBe(42);
expect(maskitoParseNumber('lbs. 1 000')).toBe(1000);
expect(maskitoParseNumber('lbs. 1 000')).toBe(1000);
});

it('parses DECIMAL number with prefix "lbs. "', () => {
expect(maskitoParseNumber('lbs. 0.42')).toBe(0.42);
expect(maskitoParseNumber('lbs. .42')).toBe(0.42);
expect(maskitoParseNumber('lbs. 1 000.42')).toBe(1000.42);
expect(maskitoParseNumber('lbs. 1 000.42')).toBe(1000.42);

const zeroWidthSpace = '\u200B';

expect(maskitoParseNumber(`lbs.${zeroWidthSpace}1 000.42`)).toBe(1000.42);
});
});
});

describe('NaN', () => {
Expand Down

0 comments on commit ff15578

Please sign in to comment.