Skip to content

Instantly share code, notes, and snippets.

@ChaseWest
Last active August 29, 2015 14:01
Show Gist options
  • Save ChaseWest/0fc910c291cd9f17d0db to your computer and use it in GitHub Desktop.
Save ChaseWest/0fc910c291cd9f17d0db to your computer and use it in GitHub Desktop.
function is(val, type){
switch(type){
case "finite":
return typeof val === "number" && Number.isFinite(val);
case "integer":
return typeof val === "number" && Number.isInteger(val);
case "NaN":
return typeof val === "number" && Number.isNaN(val);
case "positive":
return typeof val === "number" && val >= 0;
case "negative":
return typeof val === "number" && val < 0;
case "even":
return typeof val === "number" && val%2 === 0;
case "odd":
return typeof val === "number" && val%2 === 1;
case "null":
return typeof val === "object" && !val;
case "array":
return typeof val === "object" && Object.prototype.toString.call(val) === '[object Array]';
case "object":
return typeof val === "object" && !!val;
default:
return typeof val === type;
}
}
console.log(is(undefined, "undefined"));//true
console.log(is(3, "undefined"));//false
console.log(is(true, "boolean"));//true
console.log(is(3, "boolean"));//false
console.log(is(3, "number"));//true
console.log(is(null, "number"));//false
console.log(is(3, "finite"));//I believe you see the pattern here
console.log(is(undefined, "finite"));//by now
console.log(is(3, "integer"));
console.log(is(true, "integer"));
console.log(is(NaN, "NaN"));
console.log(is(3, "NaN"));
console.log(is(3, "odd"));
console.log(is(4, "odd"));
console.log(is(4, "even"));
console.log(is(3, "even"));
console.log(is("test", "string"));
console.log(is(3, "string"));
console.log(is(null, "null"));
console.log(is({}, "null"));
console.log(is([], "array"));
console.log(is(null, "array"));
console.log(is({}, "object"));
console.log(is(null, "object"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment