Skip to content

Commit

Permalink
feat: digits iterable supports negative numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
TanyaLagodich committed Sep 6, 2024
1 parent 948925d commit cc0d00b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/core/DigitsIterable.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
export class DigitsIterable {
constructor(number) {
if (typeof number === 'bigint' || number > Number.MAX_SAFE_INTEGER) {
this.number = BigInt(number);
this.number = number >= 0n ? BigInt(number) : BigInt(number) * -1n;
} else {
this.number = number;
const integerPart = Math.trunc(number);
const fractionalPart = number - integerPart;

if (fractionalPart !== 0) {
throw new RangeError(`The number ${number} cannot be converted to an Iterable because it is not an integer`);
}
this.number = Math.abs(number);
}
}

Expand Down
18 changes: 18 additions & 0 deletions src/core/__tests__/DigitsIterable.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,22 @@ describe('DigitsIterable', () => {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
]);
});

it('should work with negative integers', () => {
const digits = new DigitsIterable(-123);
const result = [...digits];
expect(result).toEqual([3, 2, 1]);
});

it('should work with negative Bigint', () => {
const digits = new DigitsIterable(BigInt(-123n));
const result = [...digits];
expect(result).toEqual([3, 2, 1]);
});

it('shouldn\'t work with decimal integers', () => {
const digitsIter = () => new DigitsIterable(123.45);
expect(digitsIter).toThrow(RangeError);
expect(digitsIter).toThrow('The number 123.45 cannot be converted to an Iterable because it is not an integer');
});
});

0 comments on commit cc0d00b

Please sign in to comment.