Last active
April 14, 2021 07:40
-
-
Save marcocesarato/8e5db06b1ae997b9138136fc497376ba to your computer and use it in GitHub Desktop.
Check if variable is empty on javascript
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
/** | |
* Is empty | |
* @param x | |
* @returns {boolean} | |
*/ | |
export const isEmpty = (x) => { | |
// Generic | |
if (typeof x !== "boolean" && !x) { | |
return true; | |
} | |
// Strings | |
if (typeof x === "string") { | |
x = x.replace(/^\s+|\s+$|\s+(?=\s)/g, ""); | |
return x === ""; | |
} | |
// Nulls and undefined | |
if (x == null) { | |
return true; | |
} | |
// Arrays | |
if (Array.isArray(x) && x.length === 0) { | |
return true; | |
} | |
// Functions | |
if (Object.prototype.toString.call(x).indexOf("Function") > -1) { | |
let m = x.toString().match(/{([\s\S]*)}/m)[1]; | |
let body = m.replace(/^\s*\/\/.*$/gm, ""); | |
return isEmpty(body); | |
} | |
// Objects | |
if (typeof x === "object") { | |
if (Object.keys(x).length === 0) { | |
return true; | |
} | |
for (let key in x) { | |
if (x.hasOwnProperty(key) && !isEmpty(x[key])) { | |
return false; | |
} | |
} | |
return true; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment