From bde4b26cfd2f2a864d1d001fe99b3c81350287e5 Mon Sep 17 00:00:00 2001 From: sarthakgupta1907-cell Date: Mon, 2 Nov 2026 18:33:21 +0530 Subject: [PATCH] feat: add octal to decimal conversion --- Conversions/OctalToDecimal.js | 24 ++++++++++++++ Conversions/test/OctalToDecimal.test.js | 43 +++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 Conversions/OctalToDecimal.js create mode 100644 Conversions/test/OctalToDecimal.test.js diff --git a/Conversions/OctalToDecimal.js b/Conversions/OctalToDecimal.js new file mode 100644 index 0000000000..4c65e9a5eb --- /dev/null +++ b/Conversions/OctalToDecimal.js @@ -0,0 +1,24 @@ +/** + * @function octalToDecimal + * @description Converts an octal number (base-8) string to its decimal + * (base-10) equivalent without using JavaScript's built-in parseInt. + * @param {string} octal - A string representing an octal number + * @returns {number} - The decimal equivalent of the octal number + * @see https://en.wikipedia.org/wiki/Octal + * @example octalToDecimal("10") => 8 + * @example octalToDecimal("377") => 255 + * @example octalToDecimal("0") => 0 + */ +const octalToDecimal = (octal) => { + if (typeof octal !== 'string' || !/^[0-7]+$/.test(octal)) { + throw new TypeError( + 'Input must be an octal string containing only digits 0-7' + ) + } + return octal + .split('') + .reverse() + .reduce((acc, digit, index) => acc + Number(digit) * Math.pow(8, index), 0) +} + +export { octalToDecimal } diff --git a/Conversions/test/OctalToDecimal.test.js b/Conversions/test/OctalToDecimal.test.js new file mode 100644 index 0000000000..5f010e12e4 --- /dev/null +++ b/Conversions/test/OctalToDecimal.test.js @@ -0,0 +1,43 @@ +import { octalToDecimal } from '../OctalToDecimal.js' + +describe('octalToDecimal', () => { + test("octalToDecimal('0') returns 0", () => { + expect(octalToDecimal('0')).toBe(0) + }) + + test("octalToDecimal('1') returns 1", () => { + expect(octalToDecimal('1')).toBe(1) + }) + + test("octalToDecimal('7') returns 7", () => { + expect(octalToDecimal('7')).toBe(7) + }) + + test("octalToDecimal('10') returns 8", () => { + expect(octalToDecimal('10')).toBe(8) + }) + + test("octalToDecimal('100') returns 64", () => { + expect(octalToDecimal('100')).toBe(64) + }) + + test("octalToDecimal('377') returns 255", () => { + expect(octalToDecimal('377')).toBe(255) + }) + + test("octalToDecimal('1000') returns 512", () => { + expect(octalToDecimal('1000')).toBe(512) + }) + + test('throws TypeError for invalid octal string', () => { + expect(() => octalToDecimal('89')).toThrow(TypeError) + }) + + test('throws TypeError for empty string', () => { + expect(() => octalToDecimal('')).toThrow(TypeError) + }) + + test('throws TypeError for non-string input', () => { + expect(() => octalToDecimal(10)).toThrow(TypeError) + }) +})