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);
}
@jonisar
Copy link

jonisar commented Feb 11, 2016

much shorter option from www.cocycles.com:
function ishex(c) {
return ('0123456789ABCDEFabcdef'.indexOf(c) > -1);
}

http://cocycles.com/search/is%20hex/1/unit/003248396001100002953

@markmercer10
Copy link

jonisar this assumes that c is only 1 character.

@q2p
Copy link

q2p commented Mar 18, 2020

jonisar this assumes that c is only 1 character.

Have you heard about for cycles? Maybe, IDK, iterate over the list of characters?

@markmercer10
Copy link

jonisar this assumes that c is only 1 character.

Have you heard about for cycles? Maybe, IDK, iterate over the list of characters?

That's what this does
var isHex = function(str) {
str = str.split('');
var parseHexIsFinite = compose(parseHex, isFinite);
return str.map(parseHexIsFinite).reduce(and);
}

@q2p
Copy link

q2p commented Mar 18, 2020

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:

  1. Faster
  2. 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.

@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