Here is the Math.max code in Chrome V8 engine.
function MathMax(arg1, arg2) { // length == 2
var length = %_ArgumentsLength();
if (length == 2) {
arg1 = TO_NUMBER(arg1);
arg2 = TO_NUMBER(arg2);
if (arg2 > arg1) return arg2;
if (arg1 > arg2) return arg1;
if (arg1 == arg2) {
// Make sure -0 is considered less than +0.
return (arg1 === 0 && %_IsMinusZero(arg1)) ? arg2 : arg1;
}
// All comparisons failed, one of the arguments must be NaN.
return NaN;
}
var r = -INFINITY;
for (var i = 0; i < length; i++) {
var n = %_Arguments(i);
n = TO_NUMBER(n);
// Make sure +0 is considered greater than -0.
if (NUMBER_IS_NAN(n) || n > r || (r === 0 && n === 0 && %_IsMinusZero(r))) {
r = n;
}
}
return r;
}
Here is the repository.
Below is how to implement the functions if Math.min() and Math.max() did not exist.
Functions have an arguments object, which you can iterate through to get its values.
It's important to note that Math.min() with no arguments returns Infinity, and Math.max() with no arguments returns -Infinity.
function min() {
var result= Infinity;
for(var i in arguments) {
if(arguments[i] < result) {
result = arguments[i];
}
}
return result;
}
function max() {
var result= -Infinity;
for(var i in arguments) {
if(arguments[i] > result) {
result = arguments[i];
}
}
return result;
}
//Tests
console.log(min(5,3,-2,4,14)); //-2
console.log(Math.min(5,3,-2,4,14)); //-2
console.log(max(5,3,-2,4,14)); //14
console.log(Math.max(5,3,-2,4,14)); //14
console.log(min()); //Infinity
console.log(Math.min()); //Infinity
console.log(max()); //-Infinity
console.log(Math.max()); //-Infinity
For this answer I will assume you have the answers put in an Array.
You can first use this function to find the max value of the array:
var maxValue = Math.max.apply(null, array);
Then you can find the amount of times this value occurs by using the following:
array.sort();
var nrOfMaxValue = array.lastIndexOf(maxValue) - array.indexOf(maxValue);
Hope this works for you!
edit: I just figured, if you only want to know if the max answer was given more than once you can just do this, without sorting the array:
var maxValue = Math.max.apply(null, array);
var onlyOnceAnswered = array.lastIndexOf(maxValue) == array.indexOf(maxValue);
So write your own function for this, like this:
function maxFindAndCount(listOfNumbers) {
var result = { max: null, count: 0 };
result.max = Math.max(listOfNumbers);
for (var l in listOfNumbers) {
if (listOfNumbers[l] == result.max)
result.count++;
}
return result;
}
Usage:
var listOfNumbers = [1,2,3,4,4];
var result = maxFindAndCount(listOfNumbers);
var max = result.max;
var count = result.count;