โจJS-style numbers
๐ง under construction
JS โฉ value โฉ object โฉ regex โฉ example โฉ JS-style numbers
replit โฉ JS-style numbers
'use strict'; // toggle sloppy/strict mode
const { log } = console;
// โญ pattern for JS-style numbers
const numberPattern = /^[+\-]?(\d+(\.\d*)?|\.\d+)([eE][+\-]?\d+)?$/;
// โฐโ1โโโฏ โฐโโโโ2โโโโโฏ โฐโ3โโฏ โฐโโโโโโ4โโโโโโโโฏ
// 1. optional + / -
// 2. digits with optional decimal part
// 3. decimal point (.) with mandantory decimal part
// 4. optional exponent part
const examples = [
"1", "-1", "+15", "1.55", ".5", "5.",
"1.3e2", "1E-4", "1e+12",
];
const counterExamples = [
"1a", "+-1", "1.2.3", "1+1", "1e4.5",
".5.", "1f5", ".",
];
let allTestsPassed = true;
// Tests:
for (let str of examples) {
if (!numberPattern.test(str)) {
log(`Failed to match '${str}'`);
allTestsPassed = false;
}
}
for (let str of counterExamples) {
if (numberPattern.test(str)) {
log(`Incorrectly accepted '${str}'`);
allTestsPassed = false;
}
}
if (allTestsPassed) log(`โ
all tests passed ...`);
// โ
all tests passed ...
Last updated