From abc73da0e1bfbb3bba99ad3cbd175c2a43896a0b Mon Sep 17 00:00:00 2001 From: Navindu Date: Thu, 31 Oct 2024 23:36:56 +0530 Subject: [PATCH] feat: added isolateDecimal --- maths/decimal_isolation.ts | 23 +++++++++++++++++++++++ maths/test/decimal_isolation.test.ts | 16 ++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 maths/decimal_isolation.ts create mode 100644 maths/test/decimal_isolation.test.ts diff --git a/maths/decimal_isolation.ts b/maths/decimal_isolation.ts new file mode 100644 index 00000000..b25faabb --- /dev/null +++ b/maths/decimal_isolation.ts @@ -0,0 +1,23 @@ +/** + * @function isolateDecimal + * @description Isolate the decimal part of a number. + * @param {number} num - The number to isolate the decimal part from. + * @returns {Object} - Object containing the integral part and the decimal part. + * @throws {TypeError} - when the input is not a number. + * @example isolateDecimal(3.14) => { integralPart: 3, decimalPart: 0.14 } + */ + +export const isolateDecimal = ( + num: number +): { integralPart: number; decimalPart: number } => { + if (typeof num !== 'number') { + throw new TypeError('Input must be a number') + } + + num = Math.abs(num) + + const integralPart = Math.trunc(num) + const decimalPart = num - integralPart + + return { integralPart, decimalPart: Number(decimalPart.toFixed(10)) } +} diff --git a/maths/test/decimal_isolation.test.ts b/maths/test/decimal_isolation.test.ts new file mode 100644 index 00000000..0c4d24aa --- /dev/null +++ b/maths/test/decimal_isolation.test.ts @@ -0,0 +1,16 @@ +import { isolateDecimal } from '../decimal_isolation' + +describe('isolateDecimal', () => { + test('isolate the decimal part of a number', () => { + expect(isolateDecimal(3.14)).toEqual({ integralPart: 3, decimalPart: 0.14 }) + expect(isolateDecimal(0.14)).toEqual({ integralPart: 0, decimalPart: 0.14 }) + expect(isolateDecimal(-3.14)).toEqual({ + integralPart: 3, + decimalPart: 0.14 + }) + }) + + test('throws an error when the input is not a number', () => { + expect(() => isolateDecimal('3.14' as unknown as number)).toThrow(TypeError) + }) +})