Skip to content

Commit bde4b26

Browse files
feat: add octal to decimal conversion
1 parent 5c39e87 commit bde4b26

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

‎Conversions/OctalToDecimal.js‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @function octalToDecimal
3+
* @description Converts an octal number (base-8) string to its decimal
4+
* (base-10) equivalent without using JavaScript's built-in parseInt.
5+
* @param {string} octal - A string representing an octal number
6+
* @returns {number} - The decimal equivalent of the octal number
7+
* @see https://en.wikipedia.org/wiki/Octal
8+
* @example octalToDecimal("10") => 8
9+
* @example octalToDecimal("377") => 255
10+
* @example octalToDecimal("0") => 0
11+
*/
12+
const octalToDecimal = (octal) => {
13+
if (typeof octal !== 'string' || !/^[0-7]+$/.test(octal)) {
14+
throw new TypeError(
15+
'Input must be an octal string containing only digits 0-7'
16+
)
17+
}
18+
return octal
19+
.split('')
20+
.reverse()
21+
.reduce((acc, digit, index) => acc + Number(digit) * Math.pow(8, index), 0)
22+
}
23+
24+
export { octalToDecimal }
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { octalToDecimal } from '../OctalToDecimal.js'
2+
3+
describe('octalToDecimal', () => {
4+
test("octalToDecimal('0') returns 0", () => {
5+
expect(octalToDecimal('0')).toBe(0)
6+
})
7+
8+
test("octalToDecimal('1') returns 1", () => {
9+
expect(octalToDecimal('1')).toBe(1)
10+
})
11+
12+
test("octalToDecimal('7') returns 7", () => {
13+
expect(octalToDecimal('7')).toBe(7)
14+
})
15+
16+
test("octalToDecimal('10') returns 8", () => {
17+
expect(octalToDecimal('10')).toBe(8)
18+
})
19+
20+
test("octalToDecimal('100') returns 64", () => {
21+
expect(octalToDecimal('100')).toBe(64)
22+
})
23+
24+
test("octalToDecimal('377') returns 255", () => {
25+
expect(octalToDecimal('377')).toBe(255)
26+
})
27+
28+
test("octalToDecimal('1000') returns 512", () => {
29+
expect(octalToDecimal('1000')).toBe(512)
30+
})
31+
32+
test('throws TypeError for invalid octal string', () => {
33+
expect(() => octalToDecimal('89')).toThrow(TypeError)
34+
})
35+
36+
test('throws TypeError for empty string', () => {
37+
expect(() => octalToDecimal('')).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for non-string input', () => {
41+
expect(() => octalToDecimal(10)).toThrow(TypeError)
42+
})
43+
})

0 commit comments

Comments
 (0)