JSFiddle - React, Tailwind, and code Playground
by ronilan
HTML
// Tempest Hiring Question
JavaScript
/**
* Tempest Hiring Question:
*
* Yaron (Ron) Ilan <[email protected]>
* Copyright 2016
* Fabriqué au Canada : Made in Canada
*
* https://news.ycombinator.com/item?id=12851801
* http://ca.indeed.com/job/web-application-developer-remote-c10ae2d41ae4404d
**/
/**
* sumTwoLargest will returns the sum of the two largest numeric elements in the array.
* if input is not an array, or, if the array contains something other than a number it will return null.
* if input is a single element array, it will return that elements value.
*
* @param {array} arr - an array of numbers (integers or floats).
* @return {integer} result - the sume of the two largest integers in the array.
**/
function sumTwoLargest (arr) {
'use strict';
// return null for anything that can't be computed
var result = null;
var i,
max,
first,
second;
if (arr.constructor === Array && !arr.some(isNaN)) {
max = arr.length;
// one element
if (max === 1) {
result = arr[0];
}
// loop the elements to extract two biggest
if (max > 1) {
// init first is largest
if (arr[0] > arr[1]) {
first = arr[0];
second = arr[1];
} else {
first = arr[1];
second = arr[0];
}
for (i = 2 ; i < max; i++ ) {
if (arr[i] > first) {
second = first;
first = arr[i];
} else if (arr[i] > second) {
second = arr[i];
}
}
result = first + second;
}
}
return result;
}
/** Tests
* A set of test cases for sumTwoLargest.
* Note, you may use factory functions to generate test cases.
**/
var tests = [{
case: 'not array',
expected: null
}, {
case: [],
expected: null
}, {
case: [3, 'A', 8, -20, 0],
expected: null
}, {
case: [0],
expected: 0
}, {
case: [1, 2, 3],
expected: 5
}, {
case: [-1, -2, -3],
expected: -3
}, {
case: [3, 17, 8, -20, 0],
expected: 25
}, {
case: [3, 17, 8, -20, 0, 3, 17, 8, -20, 0, 3, 17, 8,...