Today I Learned - Rocky Kev

TIL of a better way to do the classic Alternating sums test

POSTED ON:

TAGS:

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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.