-
-
Save softwarespot/81bb3a1ddda8f9058ebd to your computer and use it in GitHub Desktop.
Kata
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(() => { | |
// Add max to the Array prototype chain | |
Array.prototype.max = function () { | |
// I know they say the array will have at least one element, but that can't be guaranteed IMHO | |
const length = this.length; | |
if (length === 0) { | |
return Number.NaN; | |
} | |
let max = this[0]; | |
for (let i = 0; i < length; i++) { // i = 0 is done on purpose and not 1, to check if it's a valid number =) | |
let value = this[i]; | |
if (Object.prototype.toString.call(value) !== '[object Number]') { | |
// Lets be explicit with parsing as an integer and not leaving it up to the engine | |
value = Number.parseInt(value); | |
// Because NaN !== Number.NaN, so we must use isNaN() | |
if (Number.isNaN(value)) { | |
return Number.NaN; | |
} | |
} | |
// Strings that are numbers will be coerced by the JavaScript engine. Good 'ol JavaScript, but I parsed above | |
// to be explicit | |
if (value > max) { | |
max = value; | |
} | |
} | |
return max; | |
}; | |
// Tests | |
console.log([2,5,1,3].max()); // 5 | |
console.log([1,2,3,8,4,9,7,42,99].max()); // 99 | |
console.log([2,'5',1,3].max()); // 5 | |
console.log([2,5,1,'ab'].max()); // NaN | |
})(); // IIFE, for creating an anonymous scope and not polluting the global scope |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment