Skip to content

Instantly share code, notes, and snippets.

@moimikey
Last active April 27, 2019 13:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moimikey/398a99ac682ad6819f6b to your computer and use it in GitHub Desktop.
Save moimikey/398a99ac682ad6819f6b to your computer and use it in GitHub Desktop.
30 bytes to coerce "23" to Number, keep "apple" as String
/**
* function coerce(x) {
* return ''+x===x?(p=~~+x?r=+x:r=x):r=x
* }
* > undefined
* coerce(123)
* > 123
* coerce('123')
* > 123
* coerce('apple')
* > "apple"
* coerce(2.343344555)
* > 2.343344555
* coerce('2.3243499348')
* > 2.3243499348
*/
''+x===x?(p=~~+x?r=+x:r=x):r=x
@moimikey
Copy link
Author

''+x === x
? (
    p = ~~+x
    ? r = +x
    : r = x
  )
: r = x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment