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); | |
} |
That's what this does
var isHex = function(str) {
str = str.split('');
var parseHexIsFinite = compose(parseHex, isFinite);
return str.map(parseHexIsFinite).reduce(and);
}
You don't need so much obscure code to figure out if string is hexadecimal.
It runs slow and it is hard to read. What is the benefit then?
You can just iterate over the list of graphems in a loop and it will be:
- Faster
- Much easier to read
function is_hex(string) {
for (const c of string) {
if ("0123456789ABCDEFabcdef".indexOf(c) === -1) {
return false;
}
}
return true;
}
Don't overcomplicate things, when it's not necessary.
function isHex(str) {
return /^[A-F0-9]+$/i.test(str)
}
Should be most performant and easy to understand.
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
That's what this does
var isHex = function(str) {
str = str.split('');
var parseHexIsFinite = compose(parseHex, isFinite);
return str.map(parseHexIsFinite).reduce(and);
}