Skip to content

Instantly share code, notes, and snippets.

@willwalker753
Created February 20, 2020 01:33
Show Gist options
  • Save willwalker753/0e0b956843cf988c41e8b8b341e2b3d0 to your computer and use it in GitHub Desktop.
Save willwalker753/0e0b956843cf988c41e8b8b341e2b3d0 to your computer and use it in GitHub Desktop.
min and max (without sort) drill
function max(numbers) {
let maxnum = 0;
for (i = 0; i <= numbers.length; i++) {
if (maxnum < numbers[i]) {
maxnum = numbers[i];
}
}
if (numbers.length === 0) {
return null;
}
return maxnum;
}
function min(numbers) {
let minnum = 999999999;
for (i = 0; i <= numbers.length; i++) {
if (minnum > numbers[i]) {
minnum = numbers[i];
}
}
if (numbers.length === 0) {
return null;
}
return minnum;
}
/* From here down, you are not expected to
understand.... for now :)
Nothing to see here!
*/
let numbers = [1,5,8,12];
console.log(max(numbers));
console.log(min(numbers));
function testFunctionWorks(fn, input, expected) {
if (fn(input) === expected) {
console.log('SUCCESS: `' + fn.name + '` works on `[' + input + ']`');
return true;
} else {
console.log(
'FAILURE: `' +
fn.name +
'([' +
input +
'])` should be ' +
expected +
' but was ' +
fn(input)
);
return false;
}
}
function testEmpty(fn) {
if (fn([]) === null || fn([]) == undefined) {
console.log(`SUCCESS: ${fn.name} works on empty arrays`);
return true;
} else {
console.log(
`FAILURE: ${fn.name} should return undefined or null for empty arrays`
);
return false;
}
}
(function runTests() {
// we'll use the variables in our test cases
const numList1 = [-5, 28, 98, -20013, 0.7878, 22, 115];
const realMin1 = numList1[3];
const realMax1 = numList1[6];
const numList2 = [0, 1, 2, 3, 4];
const realMin2 = numList2[0];
const realMax2 = numList2[4];
const testResults = [
testFunctionWorks(max, numList1, realMax1),
testFunctionWorks(max, numList2, realMax2),
testFunctionWorks(min, numList1, realMin1),
testFunctionWorks(min, numList2, realMin2),
testEmpty(max),
testEmpty(min),
];
const numPassing = testResults.filter(function(result) {
return result;
}).length;
console.log(numPassing + ' out of ' + testResults.length + ' tests passing.');
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment