diff --git a/maths/binary_to_decimal.ts b/maths/binary_to_decimal.ts new file mode 100644 index 00000000..a68108b6 --- /dev/null +++ b/maths/binary_to_decimal.ts @@ -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 +} diff --git a/maths/test/binary_to_decimal.test.ts b/maths/test/binary_to_decimal.test.ts new file mode 100644 index 00000000..f5fff43e --- /dev/null +++ b/maths/test/binary_to_decimal.test.ts @@ -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) + }) +})