diff --git a/.github/workflows/learning_github_actions.yml b/.github/workflows/learning_github_actions.yml new file mode 100644 index 0000000..19a75da --- /dev/null +++ b/.github/workflows/learning_github_actions.yml @@ -0,0 +1,12 @@ +name: learning-github-actions +on: [push] +jobs: + run-test-case: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: "16" + - run: yarn + - run: yarn test diff --git a/lib/add.js b/lib/add.js index 1714b95..2d90eca 100644 --- a/lib/add.js +++ b/lib/add.js @@ -1,5 +1,36 @@ function add() { // 实现该函数 + if(arguments.length !== 2){ + throw new Error('wrong argument'); + } + let a = '' + arguments[0]; + let b = '' + arguments[1]; + if(isNaN(parseInt(a)) || isNaN(parseInt(b))){ + throw new TypeError('wrong type'); + } + + a = a.split(''); + b = b.split(''); + let lenA = a.length; + let lenB = b.length; + let temp = []; + let len = lenA > lenB ? lenA : lenB; + + let tempA = 0; + let tempB = 0; + for(let i=1;i<=len;i++){ + tempA = a[lenA-i] || 0; + tempB = b[lenB-i] || 0; + temp.push(parseInt(tempA)+parseInt(tempB)); + } + + for(let j=0;j= 10){ + temp[j+1] += 1; + temp[j] -= 10; + } + } + return temp.reverse().join(''); } module.exports = add \ No newline at end of file diff --git a/test/test.spec.js b/test/test.spec.js index 935b70e..901620a 100644 --- a/test/test.spec.js +++ b/test/test.spec.js @@ -1,6 +1,21 @@ var add = require('../lib/add') describe('大数相加add方法', function () { + + test('参数不等于两个时,提示参数错误',function(){ + expect( + ()=>{ + add('123') + } + ).toThrow(Error) + }) + + test('非数字类型或字符类型数字时报错',function(){ + expect(()=>{ + add('abc','123'); + }).toThrow(TypeError); + }) + test('字符串"42329"加上字符串"21532"等于"63861"', function () { expect(add('42329', '21532')).toBe('63861') }) @@ -8,4 +23,12 @@ describe('大数相加add方法', function () { test('"843529812342341234"加上"236124361425345435"等于"1079654173767686669"', function () { expect(add('843529812342341234', '236124361425345435')).toBe('1079654173767686669') }) + + test('"123456"加上"123"等于123579',function(){ + expect(add('123456',123)).toBe('123579'); + }) + + test('"123456"加上"999"等于12455',function(){ + expect(add('123456',999)).toBe('124455'); + }) }) \ No newline at end of file