From 024226ef7da50059f4c9f95812f4dd0cf850ad48 Mon Sep 17 00:00:00 2001 From: CrashedBboy Date: Thu, 29 Oct 2015 22:23:27 +0800 Subject: [PATCH] Homework 4 --- calculator.js | 13 ++++++++++++- index.html | 2 ++ main.js | 25 ++++++++++++++++--------- test/test_calculator.js | 21 +++++++++++++++++++++ 4 files changed, 51 insertions(+), 10 deletions(-) diff --git a/calculator.js b/calculator.js index caf34db..e19bf10 100644 --- a/calculator.js +++ b/calculator.js @@ -1,5 +1,5 @@ function isNumber(numStr){ - var re = /^[0-9\.]+$/; + var re = /^-?([0-9\.])+$/; return re.test(numStr); } @@ -11,5 +11,16 @@ function substract(num1, num2){ return num1 - num2; } +function multiply(num1, num2){ + return num1 * num2; +} + +function divide(num1, num2){ + return num1 / num2; +} + module.exports.add = add; +module.exports.substract = substract; +module.exports.multiply = multiply; +module.exports.divide = divide; module.exports.isNumber = isNumber; diff --git a/index.html b/index.html index cc6a9d9..ec5f210 100644 --- a/index.html +++ b/index.html @@ -22,6 +22,8 @@

Silly Calculator

=
diff --git a/main.js b/main.js index 957a234..1f1e3b7 100644 --- a/main.js +++ b/main.js @@ -10,14 +10,21 @@ window.onload = function(){ var num1 = parseFloat(num1Str) var num2 = parseFloat(num2Str) var operator = document.getElementById('operator').value; - if (operator == "add"){ - document.getElementById('ans').value = add(num1, num2); - } - else if (operator == "substract"){ - document.getElementById('ans').value = substract(num1, num2); - } - else { - alert("Bad operator!") - } + switch (operator) { + case "add": + document.getElementById('ans').value = add(num1, num2); + break; + case "substract": + document.getElementById('ans').value = substract(num1, num2); + break; + case "multiply": + document.getElementById('ans').value = multiply(num1, num2); + break; + case "divide": + document.getElementById('ans').value = divide(num1, num2); + break; + default: + alert("Bad operator!"); + } } } diff --git a/test/test_calculator.js b/test/test_calculator.js index 13f6205..0da2f81 100644 --- a/test/test_calculator.js +++ b/test/test_calculator.js @@ -7,4 +7,25 @@ describe('Calculator', function(){ assert.equal('2', cal.add(1, 1)); }) }) + describe('substract', function(){ + it('substract', function(){ + assert.equal('3', cal.substract(4, 1)); + }) + }) + describe('multiply', function(){ + it('', function(){ + assert.equal('2', cal.multiply(1, 2)); + }) + }) + describe('divide', function(){ + it('divide', function(){ + assert.equal('2', cal.divide(2, 1)); + }) + }) + describe('isNumber', function(){ + it('isNumber', function(){ + assert.equal('1', cal.isNumber(1)); + assert.equal('0', cal.isNumber('YOLO')); + }) + }) })