Skip to content

Commit

Permalink
Merge pull request #3 from tal7aouy/feat
Browse files Browse the repository at this point in the history
fix tests
  • Loading branch information
tal7aouy authored Sep 20, 2024
2 parents 9dd3585 + e6a62c2 commit 86a59e4
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 14 deletions.
1 change: 0 additions & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,4 @@ jobs:
with:
node-version: '16'
- run: npm install --production=false
- run: npx eslint . --ext .ts
- run: npm test
23 changes: 13 additions & 10 deletions src/aveta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,32 +123,35 @@ function aveta(value: number, options?: Partial<IOptions>): string {
return `${prefix}${formatted}${space}${suffix}`;
}

function avetaReverse(formattedValue: string, options?: Partial<IOptions>): number {
function avetaReverse(
formattedValue: string,
options?: Partial<IOptions>,
): number {
const opts: IOptions = options ? { ...Options, ...options } : Options;

// Remove any spaces and convert to uppercase for consistency
const cleanedValue = formattedValue.replace(/\s/g, '').toUpperCase();

// Extract the numeric part and the unit
const match = cleanedValue.match(/^(-?\(?)([\d.,]+)([A-Z]*)(\)?)?$/);
if (!match) {
throw new Error('Invalid formatted value');
}

const [, sign, numericPart, unit] = match;

// Parse the numeric part
const number = parseFloat(numericPart.replace(opts.separator, '.'));

// Find the unit index
const unitIndex = opts.units.findIndex(u => u.toUpperCase() === unit);
const unitIndex = opts.units.findIndex((u) => u.toUpperCase() === unit);

if (unitIndex === -1 && unit !== '') {
throw new Error('Unknown unit');
}

let originalValue = number * Math.pow(opts.base ?? 1000, unitIndex);

// Adjust for potential rounding errors
const magnitude = Math.pow(10, opts.precision);
originalValue = Math.round(originalValue * magnitude) / magnitude;
Expand Down
5 changes: 2 additions & 3 deletions test/aveta.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {aveta,avetaReverse} from '../src/aveta';
import { aveta, avetaReverse } from '../src/aveta';

describe('aveta test', () => {
it('returns a string', () => {
Expand Down Expand Up @@ -109,7 +109,6 @@ describe('aveta test', () => {
});
});


describe('avetaReverse', () => {
test('should correctly reverse basic formatted values', () => {
expect(avetaReverse('1K')).toBe(1000);
Expand Down Expand Up @@ -158,4 +157,4 @@ describe('avetaReverse', () => {
expect(avetaReverse('1K', { base: 1024 })).toBe(1024);
expect(avetaReverse('1M', { base: 1024 })).toBe(1048576);
});
});
});

0 comments on commit 86a59e4

Please sign in to comment.