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
18 changes: 18 additions & 0 deletions maths/binary_to_decimal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* @function binaryToDecimal
* @description Convert binary string to decimal.
* @param {string} str - The binary input.
* @return {number} - Decimal value of str.
* @example binaryToDecimal('1100') = 12
* @example binaryToDecimal('1110') = 14
*/

export const binaryToDecimal = (str: string): number => {
let number = 0

for (let i = 0; i < str.length; i++) {
number = number * 2 + Number(str[i])
}

return number
}
27 changes: 27 additions & 0 deletions maths/test/binary_to_decimal.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { binaryToDecimal } from '../binary_to_decimal'

describe('binaryToDecimal', () => {
it('should return the correct value', () => {
expect(binaryToDecimal('100')).toBe(4)
})

it('should return the correct value', () => {
expect(binaryToDecimal('1100')).toBe(12)
})

it('should return the correct value of the sum from two numbers', () => {
expect(binaryToDecimal('1110')).toBe(12 + 2)
})

it('should return the correct value of the subtract from two numbers', () => {
expect(binaryToDecimal('10111101')).toBe(245 - 56)
})

it('should return the correct value', () => {
expect(binaryToDecimal('11111110')).toBe(254)
})

it('should return the correct value', () => {
expect(binaryToDecimal('1111011111111011')).toBe(63483)
})
})