From 30896526c5cfa8c1206ef8c9acc15368d5d02b4d Mon Sep 17 00:00:00 2001 From: Steven Liu Date: Thu, 12 Dec 2019 15:23:29 +0000 Subject: [PATCH] Added #376 UInt64 operation --- src/model/UInt64.ts | 33 +++++++++++++++++++++++++++++++++ test/model/UInt64.spec.ts | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) diff --git a/src/model/UInt64.ts b/src/model/UInt64.ts index 05c21a4521..88586fcd4a 100644 --- a/src/model/UInt64.ts +++ b/src/model/UInt64.ts @@ -147,4 +147,37 @@ export class UInt64 { const long_b = Long.fromBits(other.lower, other.higher, true); return long_a.compare(long_b); } + + /** + * UInt64 add operation + * @param other + * @returns {UInt64} + */ + public add(other: UInt64): UInt64 { + const long_value = Long.fromBits(this.lower, this.higher, true); + const long_b = Long.fromBits(other.lower, other.higher, true); + return this.longToUint64(long_value.add(long_b)); + } + + /** + * UInt64 add operation + * @param other + * @returns {UInt64} + */ + public subtract(other: UInt64): UInt64 { + const long_value = Long.fromBits(this.lower, this.higher, true); + const long_b = Long.fromBits(other.lower, other.higher, true); + if (long_value.compare(long_b) < 0) { + throw new Error('Unsigned substraction result cannot be negative.'); + } + return this.longToUint64(long_value.subtract(long_b)); + } + + /** + * Convert long value to UInt64 + * @param longValue long value + */ + private longToUint64(longValue: Long): UInt64 { + return new UInt64([longValue.getLowBitsUnsigned(), longValue.getHighBitsUnsigned()]); + } } diff --git a/test/model/UInt64.spec.ts b/test/model/UInt64.spec.ts index 7433b94933..f7500dba70 100644 --- a/test/model/UInt64.spec.ts +++ b/test/model/UInt64.spec.ts @@ -185,4 +185,41 @@ describe('Uint64', () => { expect(result).to.be.true; }); }); + + describe('Operation', () => { + it('should return added value', () => { + const value = UInt64.fromUint(100); + const other = UInt64.fromUint(1); + const result = value.add(other); + expect(result.compact()).to.be.equal(101); + }); + it('should return added value', () => { + const value = UInt64.fromUint(0); + const other = UInt64.fromUint(0); + const result = value.add(other); + expect(result.compact()).to.be.equal(0); + }); + + it('should return substract value', () => { + const value = UInt64.fromUint(100); + const other = UInt64.fromUint(1); + const result = value.subtract(other); + expect(result.compact()).to.be.equal(99); + }); + + it('should return substract value', () => { + const value = UInt64.fromUint(1); + const other = UInt64.fromUint(1); + const result = value.subtract(other); + expect(result.compact()).to.be.equal(0); + }); + + it('should return substract value', () => { + const value = UInt64.fromUint(100); + const other = UInt64.fromUint(1); + expect(() => { + other.subtract(value); + }).to.throw(Error, 'Unsigned substraction result cannot be negative.'); + }); + }); });