exportconstadd=(a:string,b:string):string=>{constre=/^\d+$/if(!re.test(a)||!re.test(b)){thrownewError(`{a} and {b} must be positive integers`)}constresult=[]a=a.split('').reverse().join('')b=b.split('').reverse().join('')letcarry=0for(leti=0;i<Math.max(a.length,b.length);i++){consta_=a.length>i?parseInt(a[i]):0constb_=b.length>i?parseInt(b[i]):0letsum=a_+b_+carrycarry=Math.floor(sum/10)if(carry!==0){sum=sum%10}result.push(String(sum))}if(carry>0){result.push(carry)}returnresult.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',)})
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Typescript includes tests
github.com/kiliman/dev-to-daily-ch...
Test