JS-style numbers

🚧 under construction

JSvalueobjectregexexample ⟩ 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