Created
May 30, 2020 07:07
-
-
Save MalikBagwala/34591596620f7b47d2609551bfaeeee3 to your computer and use it in GitHub Desktop.
JavaScript Fundaments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function is(value) { | |
const checks = { | |
get string() { | |
return value instanceof String || typeof value === "string"; | |
}, | |
get undefined() { | |
return typeof value === "undefined" || value === undefined; | |
}, | |
get null() { | |
return value === null; | |
}, | |
get symbol() { | |
return typeof value === "symbol"; | |
}, | |
get number() { | |
return typeof value === "number" || value instanceof Number; | |
}, | |
get boolean() { | |
return typeof value === "boolean" || value instanceof Boolean; | |
}, | |
get array() { | |
return value instanceof Array; | |
}, | |
get object() { | |
return value && value.constructor === Object ? true : false; | |
}, | |
get function() { | |
return typeof value === "function"; | |
}, | |
get boundFunction() { | |
// Since bind() method returns a new function without prototype we can simply check | |
// if it has a prototype or not | |
// NOTE: both arrow functions and bound functions do not have a prototype | |
return this.function && value.prototype ? false : true; | |
}, | |
get bigInt() { | |
return typeof value === "bigint" || value instanceof BigInt; | |
}, | |
get numericString() { | |
// Notice how we can resuse existing getters | |
return this.string && Number(value) ? true : false; | |
}, | |
get date() { | |
return value instanceof Date && !isNaN(value); | |
}, | |
get regExp() { | |
return value instanceof RegExp; | |
}, | |
get error() { | |
return value instanceof Error; | |
}, | |
get promise() { | |
return value instanceof Promise; | |
}, | |
get truthy() { | |
// Pretty Neat, Right? | |
return !!value; | |
}, | |
get falsy() { | |
return !value; | |
}, | |
get set() { | |
// this is the only check required since there are no set literals in javascript | |
return value instanceof Set; | |
}, | |
get map() { | |
// this is the only check required since there are no map literals in javascript | |
return value instanceof Map; | |
}, | |
get iteratable() { | |
// reference - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols | |
return Symbol.iterator in Object(value); | |
}, | |
}; | |
return new Proxy(checks, { | |
get(target, name) { | |
if (target[name] !== undefined) return target[name]; | |
throw new Error("Property Does not exist!"); | |
}, | |
}); | |
} | |
console.log(is("Malik").asdsdadadd) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment