Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Created December 13, 2024 16:10
Show Gist options
  • Save cferdinandi/bcbef7499cd47cafbaf67b7d9faaac3a to your computer and use it in GitHub Desktop.
Save cferdinandi/bcbef7499cd47cafbaf67b7d9faaac3a to your computer and use it in GitHub Desktop.
const calculator = (function () {
/**
* Add two or more numbers together
* @param {...Numbers} nums The numbers to add together
* @return Number The total
*/
function add (...nums) {
let total = 0;
for (let num of nums) {
total = total + num;
}
return total;
}
/**
* Add two or more numbers together
* @param {...Numbers} nums The numbers to add together
* @return Number The total
*/
function subtract (...nums) {
let total = nums.shift() || 0;
for (let num of nums) {
total = total - num;
}
return total;
}
return {add, subtract};
})();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Mocha Tests</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script src="https://unpkg.com/chai@4/chai.js"></script>
<script src="https://unpkg.com/mocha/mocha.js"></script>
<script class="mocha-init">
mocha.setup('bdd');
mocha.checkLeaks();
window.addEventListener('load', function () {
mocha.run();
});
</script>
<script src="calculator.js"></script>
<script src="test.calculator.js"></script>
</body>
</html>
const {expect} = chai;
describe('the add() method', function () {
it('Should add two or more numbers together', function () {
expect(calculator.add(4, 6, 8)).to.equal(18);
});
it('Should return the original value when one number is provided', function () {
expect(calculator.add(42)).to.equal(42);
});
it('Should return 0 if no numbers are provided', function () {
expect(calculator.add()).to.equal(0);
});
});
describe('the subtract() method', function () {
it('Should subtract two or more numbers', function () {
expect(calculator.subtract(8, 3, 2)).to.equal(3);
});
it('Should return the original value when one number is provided', function () {
expect(calculator.subtract(42)).to.equal(42);
});
it('Should return 0 if no numbers are provided', function () {
expect(calculator.subtract()).to.equal(0);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment