Last active
January 24, 2020 16:48
-
-
Save olaferlandsen/87738217283363769eb60739420becaf to your computer and use it in GitHub Desktop.
isEmpty is a compilation of functions to check if is a empty value on javascript compatible with ECMA5+
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
/** | |
* | |
* boolean isEmpty ( value ) | |
* | |
* Example: | |
* | |
* var a = null; | |
* if (isEmpty(a)) { | |
* alert ('empty variable'); | |
* } | |
*/ | |
function isEmpty (value) { | |
if (value == null || value == undefined) { | |
return true; | |
} | |
if (value.prop && value.prop.constructor === Array) { | |
return value.length == 0; | |
} | |
else if (typeof value == 'object') { | |
return Object.keys(value).length === 0 && value.constructor === Object | |
} | |
else if (typeof value == 'string') { | |
return value.length == 0; | |
} | |
else if (typeof value == 'number') { | |
return value == 0; | |
} else if (!value) { | |
return true; | |
} | |
return false; | |
} | |
/** | |
* | |
* Example: | |
* | |
* var a = ""; | |
* if (a.isEmpty()) { | |
* alert ('empty string'); | |
* } | |
*/ | |
String.prototype.isEmpty = function() { | |
return this.toString().length == 0; | |
}; | |
/** | |
* | |
* Example: | |
* | |
* var a = 1; | |
* if (a.isEmpty()) { | |
* alert ('empty number'); | |
* } | |
* | |
* Note: | |
* | |
* Use only with variable. | |
*/ | |
Number.prototype.isEmpty = function() { | |
return this === 0; | |
}; | |
/** | |
* | |
* Example: | |
* | |
* var a = []; | |
* if (a.isEmpty()) { | |
* alert ('empty array'); | |
* } | |
*/ | |
Array.prototype.isEmpty = function() { | |
return this.length == 0; | |
}; | |
/** | |
* | |
* Example: | |
* | |
* var a = {}; | |
* if (a.isEmpty()) { | |
* alert ('empty object'); | |
* } | |
* | |
* Note: | |
* Dont work with null value. | |
*/ | |
Object.prototype.isEmpty = function() { | |
return Object.keys(this).length === 0 && this.constructor === Object; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
"Object.prototype.isEmpty" kills Object as hash abilities