From cc0d00be98fdb9c56479528f41ef3cef507669e4 Mon Sep 17 00:00:00 2001 From: Tatiana Lagodich Date: Fri, 6 Sep 2024 21:47:41 +0400 Subject: [PATCH] feat: digits iterable supports negative numbers --- src/core/DigitsIterable.js | 10 ++++++++-- src/core/__tests__/DigitsIterable.spec.js | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/core/DigitsIterable.js b/src/core/DigitsIterable.js index 9b7cabe..14f65ef 100644 --- a/src/core/DigitsIterable.js +++ b/src/core/DigitsIterable.js @@ -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); } } diff --git a/src/core/__tests__/DigitsIterable.spec.js b/src/core/__tests__/DigitsIterable.spec.js index 23bbc12..d35448e 100644 --- a/src/core/__tests__/DigitsIterable.spec.js +++ b/src/core/__tests__/DigitsIterable.spec.js @@ -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'); + }); });