Skip to content

Commit

Permalink
chore: use byte-parser
Browse files Browse the repository at this point in the history
  • Loading branch information
hustcc committed Sep 16, 2020
1 parent d94a9db commit 6048b29
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 34 deletions.
21 changes: 0 additions & 21 deletions __tests__/parse-size.spec.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,6 @@
import { parse, format } from '../src/bytes';

describe('parse-size', () => {
test('parse', () => {
expect(parse('100')).toBe(100);
expect(parse('100b')).toBe(100);
expect(parse('100 b')).toBe(100);
expect(parse('10.1 b')).toBe(10.1);

expect(parse('10.1 kb')).toBe(10.1 * 1024);
expect(parse('10.1 KB')).toBe(10.1 * 1024);

expect(parse('1.2 mb')).toBe(1.2 * 1024 * 1024);
expect(parse('1.2 mb')).toBe(1.2 * 1024 * 1024);

expect(parse('1.2 mb')).toBe(1.2 * 1024 * 1024);

expect(parse('1.2 Gb')).toBe(1.2 * 1024 * 1024 * 1024);

expect(() => {
parse('1a.2 mb');
}).toThrow(`file size string '1a.2 mb' syntax error, e.g. 100 b, 1.2 Kb, 2 Mb, 20.5 Gb!`);
});

test('format', () => {
expect(format(100)).toBe('100.0 b');
expect(format(10000)).toBe('9.8 Kb');
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"prepublishOnly": "npm run build"
},
"dependencies": {
"byte-parser": "^1.0.0",
"chalk": "^4.1.0",
"commander": "^6.1.0"
},
Expand Down
16 changes: 3 additions & 13 deletions src/bytes.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,13 @@
const JEDEC = { radix: 1024, unit: ['b', 'Kb', 'Mb', 'Gb'] };
import parser from 'byte-parser';

function unitToRate(unit: string) {
return unit === 'b' ? 1 : unit === 'kb' ? 1024 : unit === 'mb' ? 1024 * 1024 : unit === 'gb' ? 1024 * 1024 * 1024 : 1;
}
const JEDEC = { radix: 1024, unit: ['b', 'Kb', 'Mb', 'Gb'] };

/**
* 解析 size string
* @param sizeString
*/
export function parse(sizeString: string): number {
const match = sizeString.match(/^(\d*\.*\d*)\s*([gGkKmM]{0,1}[bB]{0,1})$/);
if (!match) {
throw new Error(`file size string '${sizeString}' syntax error, e.g. 100 b, 1.2 Kb, 2 Mb, 20.5 Gb!`);
}

const size = Number(match[1]);
const unit = match[2].toLowerCase();

return size * unitToRate(unit);
return parser(sizeString);
}

/**
Expand Down

0 comments on commit 6048b29

Please sign in to comment.