TIL of a better way to do the classic Alternating sums test
POSTED ON:
TAGS: javascript basics
This is a common test. Two teams. First value goes into Team 1. Second value goes into Team 2.
So [100, 5, 100, 5, 100, 5] becomes [300, 15];
function alternatingSums(array) {
let total = [0, 0];
let isOdd = true;
for (let i = 0; i < array.length; i++) {
isOdd ? total[0] += array[i] : total[1] += array[i];
isOdd = !isOdd;
}
return total;
}
This is using a variable true/false to control which direction the values go into.
Another solution is using the % (mod).
function alternatingSums(array) {
let evenSum = 0;
let oddSum = 0;
for(let i = 0; i < array.length; i++) {
if(i % 2 === 0) {
evenSum += array[i];
} else {
oddSum += array[i];
}
}
return [evenSum, oddSum];
}
TEST SUITE using jasmine:
describe('alternatingSums()', () => {
it('returns alternating sums of even and odd', () => {
// arrange
const nums = [50, 60, 60, 45, 70];
// act
const result = alternatingSums(nums);
// log
console.log("result: ", result);
// assert
expect(result).toEqual([180, 105]);
});
});
Related TILs
Tagged: javascript