Inlining JavaScript functions

FullStackJack

General JavaScript question here. It wasn't an easily googleable question (in my opinion) so I figured I'd ask it here to humans, and if it gets flagged as a duplicate then that's okay. It dawned on me while I was writing this function that there must be a way to write this in a way that doesn't rely on a temporary variable.

const isHex = num => {
  let result = true;
  [...num].map(n => { if (isNaN(parseInt(n,16))) result = false; });
  return result;
};

How would you inline a function like this and get rid of result? I feel like this is probably a gap in my JavaScript knowledge and I'm curious to know the answer. Maybe it's painfully obvious and this is a silly question. Idk.

Nina Scholz

You could use Array#every and return early.

const isHex = num => [...num].every(n => !isNaN(parseInt(n, 16)));
    
console.log(isHex('1a')); // true
console.log(isHex('1#')); // false

Same with Array#some.

const isHex = num => ![...num].some(n => isNaN(parseInt(n, 16)));
    
console.log(isHex('1a')); // true
console.log(isHex('1#')); // false

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related