Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "mri",
"version": "1.2.0",
"version": "1.2.1",
"description": "Quickly scan for CLI flags and arguments",
"repository": "lukeed/mri",
"module": "lib/index.mjs",
Expand Down
13 changes: 11 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,21 @@ function toArr(any) {
return any == null ? [] : Array.isArray(any) ? any : [any];
}

function toNum(val) {
if (typeof val !== 'string') return val;
var x = +val;
if (x * 0 !== 0) return val; // NaN check
// Only use BigInt for integer strings that lose precision
if (String(x) !== val && /^-?\d+$/.test(val)) return BigInt(val);
Comment thread
remorses marked this conversation as resolved.
Outdated
return x;
}

function toVal(out, key, val, opts) {
var x, old=out[key], nxt=(
!!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val))
: typeof val === 'boolean' ? val
: !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val))
: (x = +val,x * 0 === 0) ? x : val
: !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push(toNum(val)),!!val))
: toNum(val)
);
out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]);
}
Expand Down
29 changes: 29 additions & 0 deletions test/num.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,32 @@ test('already a number', t => {
t.is(typeof argv.x, 'number');
t.end();
});

test('large integers use BigInt to preserve precision', t => {
const argv = fn(['--id', '9007199254740993', '--small', '42']);
t.is(argv.id, 9007199254740993n);
t.is(typeof argv.id, 'bigint');
t.is(argv.small, 42);
t.is(typeof argv.small, 'number');
t.end();
});
Comment thread
remorses marked this conversation as resolved.
Outdated

test('MAX_SAFE_INTEGER boundary', t => {
// MAX_SAFE_INTEGER = 9007199254740991
const argv = fn([
'--safe', '9007199254740991',
'--unsafe', '9007199254740993'
]);
t.is(argv.safe, 9007199254740991);
t.is(typeof argv.safe, 'number');
t.is(argv.unsafe, 9007199254740993n);
t.is(typeof argv.unsafe, 'bigint');
t.end();
});

test('large negative integers', t => {
const argv = fn(['--id=-9007199254740993']);
t.is(argv.id, -9007199254740993n);
t.is(typeof argv.id, 'bigint');
t.end();
});
Comment thread
remorses marked this conversation as resolved.
Outdated