Skip to content

Instantly share code, notes, and snippets.

@tjmehta
Last active August 31, 2022 05:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjmehta/4636969 to your computer and use it in GitHub Desktop.
Save tjmehta/4636969 to your computer and use it in GitHub Desktop.
Function that checks if a number is Hex with Javascript (ES5)
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);
}
@tjmehta
Copy link
Author

tjmehta commented Mar 19, 2020

function isHex(str) {
  return /^[A-F0-9]+$/i.test(str)
}

Should be most performant and easy to understand.

@markmercer10
Copy link

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