Last active
August 31, 2022 05:51
-
-
Save tjmehta/4636969 to your computer and use it in GitHub Desktop.
Function that checks if a number is Hex with Javascript (ES5)
This file contains 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
var compose = function() { | |
var funcs = Array.prototype.slice.apply(arguments); | |
return function(arg) { | |
return funcs.reduce(function(arg, fn) { | |
return fn.call(this, arg); | |
}, arg); | |
}; | |
}; | |
var and = function() { | |
return Array.prototype.slice.apply(arguments).reduce(function(prev, curr) { return prev&&curr; }); | |
} | |
var parseHex = function(v) { | |
return parseInt(v, 16); | |
}; | |
var isHex = function(str) { | |
str = str.split(''); | |
var parseHexIsFinite = compose(parseHex, isFinite); | |
return str.map(parseHexIsFinite).reduce(and); | |
} |
function isHex(str) { return /^[A-F0-9]+$/i.test(str) }Should be most performant and easy to understand.
That right there is the best solution. Not sure why I didn't think of doing it with regex to begin with :-)
Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should be most performant and easy to understand.