DEV Community

Discussion on: Daily Challenge #119 - Adding Big Numbers

Collapse
 
kiliman profile image
Kiliman • Edited

Typescript includes tests

github.com/kiliman/dev-to-daily-ch...

export const add = (a: string, b: string): string => {
  const re = /^\d+$/
  if (!re.test(a) || !re.test(b)) {
    throw new Error(`{a} and {b} must be positive integers`)
  }

  const result = []
  a = a
    .split('')
    .reverse()
    .join('')
  b = b
    .split('')
    .reverse()
    .join('')
  let carry = 0
  for (let i = 0; i < Math.max(a.length, b.length); i++) {
    const a_ = a.length > i ? parseInt(a[i]) : 0
    const b_ = b.length > i ? parseInt(b[i]) : 0
    let sum = a_ + b_ + carry
    carry = Math.floor(sum / 10)
    if (carry !== 0) {
      sum = sum % 10
    }
    result.push(String(sum))
  }
  if (carry > 0) {
    result.push(carry)
  }
  return result.reverse().join('')
}

Test

import { add } from '.'

it('should throw an error if numbers are not all digits', () => {
  expect(() => add('', '')).toThrow()
  expect(() => add('abc', '321')).toThrow()
  expect(() => add('11', 'xyz')).toThrow()
})

it('should return sum of two numbers', () => {
  expect(add('0', '0')).toBe('0')
  expect(add('123', '321')).toBe('444')
  expect(add('11', '99')).toBe('110')
  expect(add('1', '199')).toBe('200')
})

it('should return sum of two really big numbers', () => {
  expect(add('123456789', '987654321')).toBe('1111111110')
  expect(add('12345678910123456789', '987654323109876543210')).toBe(
    '1000000002019999999999',
  )
})