Cengage 2nd TDD MPV
by Matthew Vasallo
HTML
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jasmine/1.3.1/jasmine.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/jasmine/1.3.1/jasmine.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jasmine/1.3.1/jasmine-html.js"></script>
<title>Jasmine Spec Runner</title>
JavaScript
function findClosestToZero(numbersArray){
var closestToZero = numbersArray[0];
for(var i=1; i<numbersArray.length; i++){
var isLessThanCurrentValue = Math.abs(numbersArray[i]) < Math.abs(closestToZero);
var isValidTie = Math.abs(numbersArray[i]) === Math.abs(closestToZero) && numbersArray[i] > 0;
if(isLessThanCurrentValue || isValidTie){
closestToZero = numbersArray[i];
}
}
return closestToZero;
}
describe('Closest to zero exercise', function () {
it('should handle array with single value', function () {
expect(findClosestToZero([1])).toBe(1);
});
it('should handle array with many positive values in varying order', function () {
expect(findClosestToZero([1, 2, 3])).toBe(1);
expect(findClosestToZero([3, 2, 1])).toBe(1);
expect(findClosestToZero([2, 1, 3])).toBe(1);
});
it('should handle array with many values with the mininum at the end', function () {
expect(findClosestToZero([5,4,7,2])).toBe(2);
});
it('should handle array with multiple negative numbers', function () {
expect(findClosestToZero([-5,-4,-7,-2])).toBe(-2);
});
it('should handle array with tie condition', function () {
expect(findClosestToZero([-3, 3])).toBe(3);
});
it('should handle array with multiple negative and positive values.', function () {
expect(findClosestToZero([2, -3, 3, -2])).toBe(2);
expect(findClosestToZero([-2, 2, 3])).toBe(2);
expect(findClosestToZero([3, 2, -2])).toBe(2);
});
it("handles an array with 0", function() {
expect(findClosestToZero([1,2,0,-1])).toBe(0);
});
});
// load jasmine htmlReporter
$(function() {
var env = jasmine.getEnv();
env.addReporter(new jasmine.HtmlReporter());
env.execute();
});