All files / string extract-number.ts

100% Statements 4/4
100% Branches 2/2
100% Functions 1/1
100% Lines 4/4

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    1x   1x                       12x 12x    
import { parseMatchedNumber } from './internal';
 
const NUMBER_SOURCE = String.raw`[+\-]?(?:\d+(?:[,.]\d+)?|[,.]\d+)`;
 
const NUMBER_PATTERN = new RegExp(NUMBER_SOURCE, 'v');
 
/**
 * Extracts the first number of a text, with `.` or `,` before the decimals: `1,234` is `1.234`.
 *
 * @param input - A text, such as a label or a sensor message.
 * @returns The first number; `undefined` when there is none.
 * @example
 * extractNumber('Speed: -12,5 kn'); // -12.5
 * extractNumber('n/a'); // undefined
 */
export function extractNumber(input: string): number | undefined {
  const match = NUMBER_PATTERN.exec(input);
  return match ? parseMatchedNumber(match[0]) : undefined;
}