Cengage 2nd round interview 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) {
let currentLowest = numbersArray[0];
numbersArray.forEach(n => {
currentLowest = (Math.abs(n) < Math.abs(currentLowest)) || (Math.abs(n) === Math.abs(currentLowest) && n > 0) ? n : currentLowest;
//currentLowest = Math.abs(n) === Math.abs(currentLowest) && n > 0 ? n : currentLowest;
});
return currentLowest;
}
describe('Closest to zero exercise', function() {
it('should have a findClosestToZero function declared', function() {
expect(typeof findClosestToZero).toBe("function");
});
it('handles 1 number', () => {
expect(findClosestToZero([1])).toBe(1);
expect(findClosestToZero([2])).toBe(2);
});
it('handles all positive numbers', () => {
expect(findClosestToZero([1, 2])).toBe(1);
expect(findClosestToZero([2, 0, 1])).toBe(0);
});
it('handles all negative numbers', () => {
expect(findClosestToZero([-1, -2])).toBe(-1);
expect(findClosestToZero([-2, -1, -3])).toBe(-1);
expect(findClosestToZero([0, -1, -3])).toBe(0);
});
it('handles both pos and neg numbers', () => {
expect(findClosestToZero([-1, -2, 3])).toBe(-1);
expect(findClosestToZero([1, -2, 3])).toBe(1);
expect(findClosestToZero([1, -2, 3, 0])).toBe(0);
});
it('handles tie condition', () => {
expect(findClosestToZero([-1, -2, 1])).toBe(1);
});
});
// load jasmine htmlReporter
$(function() {
var env = jasmine.getEnv();
env.addReporter(new jasmine.HtmlReporter());
env.execute();
});