Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for [old] Even the Last by danielsan
"use strict";
/**
* For Loop is the winner due to its the amazing performance
* as you can see here https://jsperf.com/evenlast/1
*/
/** single lined version */
// const evenLast = (a) => a.length === 0 ? 0 : a.reduce((t,v,i) => i%2 ? t : t + v, 0) * a[a.length - 1]
/** recursive. functional, immutable */
// const evenLast = (a, length = a.length, i = 0, last=a[length - 1]||0, sum = 0) => length > i ? evenLast(a, length, i + 2, last, sum + a[i]) : sum * last
/** for loop */
function evenLast(a) {
if (a.length === 0) return 0
let sum = a[0]
for(let i = 2; i < a.length; i += 2) sum += a[i]
return sum * a[a.length - 1]
}
var assert = require('assert');
if (!global.is_checking) {
let t
assert.equal(t=evenLast([0, 1, 2, 3, 4, 5]), 30, `${t} != (0+2+4)*5=30`);
assert.equal(t=evenLast([1, 3, 5]), 30, "(1+5)*5=30");
assert.equal(t=evenLast([6]), 36, "(6)*6=36");
assert.equal(t=evenLast([]), 0, "An empty array = 0");
console.log("Coding complete? Click 'Check' to review your tests and earn cool rewards!");
}
April 11, 2020