1

As the title says, I'm trying to build a function that given a string value as its input, it returns the value casted properly.

So far I got this, I think it looks ugly and have the feeling it can be solved in a better way.

Examples:

const smartCast = function (value) {
  if (value === 'true') {
    return true;
  }
  if (value === 'false') {
    return false;
  }
  if (!isNaN(value)) {
    return Number(value);
  }

  return value;
};

console.log(smartCast('ahoy!') === 'ahoy!');
console.log(smartCast('hello there') === 'hello there');
console.log(smartCast('412') === 412);
console.log(smartCast('71.3') === 71.3);
console.log(smartCast('true') === true);
console.log(smartCast('false') === false);

Let me know if there is a case I'm not taking into account.

3
  • except for booleans, if you use a ``` == ``` for checking this equality, you'll be able to get rid of the function altogether. Also instead of passing the string to smartCast why not pass the right hand variable to smartCast and have the function like ``` const smartCast2 = function (value) { return String.value(value); }; ``` ? Commented Sep 29, 2018 at 5:21
  • It would be better if you convert both to a common type and then determine the equality. Commented Sep 29, 2018 at 5:52
  • if (value === 'true') { return true; } if (value === 'false') { return false; } can be combined as if(value==='true' || value==='false'){return value==='true'} Commented Sep 29, 2018 at 6:07

2 Answers 2

2
function cast(value) {
  if (typeof value !== 'string')
    return value

  // Ignore values that would start an array or object.
  if (/^\s*[{\[]/.test(value))
    return value

  try {
    // Try to parse as some value.
    return JSON.parse(value)
  } catch(e) {
    // If there's an error, we will assume it is just
    // a string.
  }

  return value
}

console.log(typeof cast('false')) // boolean
console.log(typeof cast('true')) // boolean
console.log(typeof cast('1')) // number
console.log(typeof cast('3.14')) // number
console.log(typeof cast('abc')) // string
console.log(typeof cast('[1,2,3]')) // string
console.log(typeof cast('{"abc":1}')) // string
Sign up to request clarification or add additional context in comments.

3 Comments

…or drop the try/catch and simply feed valid JSON instead
This input "[1, 2, 3]" would return an array instead of a string. Anyway I like this answer so far.
Added a check for objects and arrays.
0

Take a look at empty string case and date https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#Examples

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.