-
-
Save tjmehta/4636969 to your computer and use it in GitHub Desktop.
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 this assumes that c is only 1 character.
jonisar this assumes that c is only 1 character.
Have you heard about for
cycles? Maybe, IDK, iterate over the list of characters?
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);
}
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
much shorter option from www.cocycles.com:
function ishex(c) {
return ('0123456789ABCDEFabcdef'.indexOf(c) > -1);
}
http://cocycles.com/search/is%20hex/1/unit/003248396001100002953