From 98f4cb1742d01acdeb6f1c538c1c38b264a25f0e Mon Sep 17 00:00:00 2001 From: Yarchik Date: Tue, 23 Jun 2026 17:09:03 +0100 Subject: [PATCH] Add the documented `b` unit to the parse regex `b` is documented as a supported, case-insensitive unit, but it is missing from the parse regex, so `b`-suffixed values fall through to the `parseInt` fallback (which truncates toward zero) instead of the unit path (which floors). The two diverge for negative fractional values: bytes.parse('-1.9b') // -1 (should be -2, like every other unit) The existing "Should drop partial bytes" test (parse('1.1b') === 1) already treats `b` as a real floored unit; it passed only because truncation and floor agree for positives. Adding `b` to the regex routes it through the same Math.floor path as kb/mb/gb/tb/pb. No new inputs are accepted, since every `b`-suffixed string already matched via the fallback. --- index.js | 2 +- test/byte-parse.js | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 6f2d0f8..62e2681 100644 --- a/index.js +++ b/index.js @@ -34,7 +34,7 @@ var map = { pb: Math.pow(1024, 5), }; -var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; +var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(b|kb|mb|gb|tb|pb)$/i; /** * Convert the given value in bytes into a string or parse to string to an integer in bytes. diff --git a/test/byte-parse.js b/test/byte-parse.js index cebfab2..13fc091 100644 --- a/test/byte-parse.js +++ b/test/byte-parse.js @@ -103,6 +103,9 @@ describe('Test byte parse function', function(){ it('Should drop partial bytes', function(){ assert.equal(bytes.parse('1.1b'), 1); assert.equal(bytes.parse('1.0001kb'), 1024); + // the `b` unit must floor like every other unit (not truncate toward zero) + assert.equal(bytes.parse('-1.9b'), -2); + assert.equal(bytes.parse('-1.9kb'), Math.floor(-1.9 * 1024)); }); it('Should allow whitespace', function(){