Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@serradura
Forked from 140bytes/LICENSE.txt
Created April 27, 2012 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serradura/2510893 to your computer and use it in GitHub Desktop.
Save serradura/2510893 to your computer and use it in GitHub Desktop.
140byt.es -- Click ↑↑ fork ↑↑ to play!

is()

Usage

// To checks if some value is numeric
is("Number", 1);     // true
is("Number", 1.2);   // true

is("Number", "1");   // true
is("Number", "1.2"); // true
is("Number", " 1 "); // true

is("Number", "");    // false
is("Number", " ");   // false
is("Number", "One"); // false


// To checks if a string is filled
is("Present", "blank");      // true
is("Present", " \n A \t ");  // true

is("Present", " ");         // false
is("Present", " \n\t ");    // false

// If you use an invalid function.
is("Foo", "Bar"); // 0

// Why ZERO? 
// Because I haven't any space to return something useful! :p
function is(k,v){
return(
k == 'Number' ? !isNaN(parseInt(v)) && isFinite(v) :
k == 'Present' ? !(v == undefined || v == null) && v.replace(/^\s+|\s+$/g,'') != '' :
0
)
}
function is(k,v){return(k=='Number'?!isNaN(parseInt(v))&&isFinite(v):k=='Present'?!(v==undefined||v==null)&&v.replace(/^\s+|\s+$/g,'')!='':0)}
DO WHAT YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Rodrigo Serradura <http://github.com/serradura>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
{
"name": "is()",
"description": "Checks if a value is numeric or is filled string",
"keywords": [
"string",
"number",
"functional"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>undefined</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
// write a small example that shows off the API for your example
// and tests it in one fell swoop.
var myFunction = function(){ /* the code here should be identical to the entry. */ }
document.getElementById( "ret" ).innerHTML = myFunction()
</script>
@maettig
Copy link

maettig commented Apr 27, 2012

I'm not sure if this is the same in all possible cases but it saves a lot of bytes. Also fixes the problem that your version crashes for is('Present', 1).

function(k,v){return k[0]=='N'?isFinite(parseInt(v)):!!(v&&(''+v).replace(/\s/g,''))}

Edit: Save more bytes. ;-)

function(k,v){return k[6]?!!(v&&(''+v).replace(/\s/g,'')):isFinite(parseInt(v))}

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