Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions Conversions/OctalToDecimal.js
Original file line number Diff line number Diff line change
@@ -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 }
43 changes: 43 additions & 0 deletions Conversions/test/OctalToDecimal.test.js
Original file line number Diff line number Diff line change
@@ -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)
})
})
Loading