JSFiddle - React, Tailwind, and code Playground
by dashk
JavaScript
var list = [1, 2, -1, 10, Number.MAX_VALUE, Number.MIN_VALUE, -Number.MIN_VALUE];
/**
* Finds the top 4 integers from given array
*
* @param {Array} input List of integers
* @return {Array}
*/
function findTopFourInteger(input) {
// If input is empty or has a length <= 4, return it directly. (No
// computation needed!)
if (input === null || input.length <= 4) {
return input;
}
var min, // Minimum value in output array
index, // Index of the minimum value in output array
output = input.slice(0, 4); // Output array (To be returned to the client)
// Helper method to update output's minimum and its index
var minHelper = function() {
// This function will be ran in constant time - Since, in the list, we
// have at most 4 elements.
// Set min and index as the first element of output array
min = output[0], index = 0;
// Loop through the remaining three
for (var j = 1; j < output.length; ++j) {
// If current element is less than current min, record its value and index.
if (output[j] < min) {
min = output[j];
index = j;
}
}
// NOTE
// This function can be simplified by doing this:
//
// min = Math.min.apply(Math, output); // Find the min in output
// index = output.indexOf(min); // Locate the index of min in output
//
// However, Array.indexOf is not supported in browser IE9-. If this code needs to
// support Node.js or modern browsers, we should replace the for-loop with the
// two statements above, making the code easier to read
};
// Since 4 elements were added to output as a part of initialization, we need to
// compute the min and its index.
minHelper();
// Loop through the remaining element in the array
for...