Skip to content

Commit

Permalink
Merge pull request #261 from yearn/feat/is-zero
Browse files Browse the repository at this point in the history
feat: Add `isZero` helper
  • Loading branch information
Majorfi committed Jun 8, 2023
2 parents 158f105 + cf3d7c5 commit db4133c
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
34 changes: 34 additions & 0 deletions packages/web-lib/utils/isZero.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import {isZero} from '@yearn-finance/web-lib/utils/isZero';

describe('isZero function', (): void => {
test('returns false when no argument given', (): void => {
expect(isZero()).toBe(false);
});

test.each([
[0, true],
['0', true],
['0.0', true],
['0,0', true],
['000', true],
[0n, true],
[`${0}`, true],
[' 0 ', true],
[' 0.00 ', true],
['-0', true],
[null, false],
[undefined, false],
[-1, false],
['1', false],
[1, false],
['-1', false],
['0.1', false],
[1n, false],
['abc', false],
[NaN, false],
['', false],
[' ', false]
])('isZero(%p) should return %s', (input, expected): void => {
expect(isZero(input)).toBe(expected);
});
});
27 changes: 27 additions & 0 deletions packages/web-lib/utils/isZero.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
type TProps = bigint | number | string | null;

export function isZero(value?: TProps): boolean {
if (value === null || value === undefined) {
return false;
}

if (typeof value === "string") {
value = value.trim().replace(',', '.');

if (value === "") {
return false;
}

// Check if the string can be parsed as a floating-point number
const parsed = Number(value);
if (!isNaN(parsed)) {
return parsed === 0;
}
}

try {
return BigInt(value) === 0n;
} catch {
return false;
}
}

0 comments on commit db4133c

Please sign in to comment.