Last active
October 23, 2020 20:18
-
-
Save EdwinBetanc0urt/3fc02172ada073ded4b52e46543553ce to your computer and use it in GitHub Desktop.
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
/** | |
* Checks if value is empty. Deep-checks arrays and objects | |
* Note: isEmpty([]) == true, isEmpty({}) == true, | |
* isEmpty([{0: false}, "", 0]) == true, isEmpty({0: 1}) == false | |
* @author EdwinBetanc0urt <EdwinBetanc0urt@oulook.com> | |
* @param {boolean|array|object|number|string|date|map|set|function} value | |
* @returns {boolean} | |
*/ | |
export const isEmptyValue = function(value) { | |
let isEmpty = false | |
const typeOfValue = typeValue(value); | |
switch (typeOfValue) { | |
case 'Undefined': | |
case 'Error': | |
case 'Null': | |
isEmpty = true; | |
break; | |
case 'Boolean': | |
case 'Date': | |
case 'Function': // Or class | |
case 'Promise': | |
case 'RegExp': | |
isEmpty = false; | |
break; | |
case 'String': | |
isEmpty = Boolean(!value.trim().length); | |
break; | |
case 'Math': | |
case 'Number': | |
if (Number.isNaN(value)) { | |
isEmpty = true; | |
break; | |
} | |
isEmpty = false; | |
break; | |
case 'JSON': | |
if (value.trim().length) { | |
isEmpty = Boolean(value.trim() === '{}'); | |
break; | |
} | |
isEmpty = true; | |
break; | |
case 'Object': | |
isEmpty = Boolean(!Object.keys(value).length); | |
break; | |
case 'Arguments': | |
case 'Array': | |
isEmpty = Boolean(!value.length); | |
break; | |
case 'Map': | |
case 'Set': | |
isEmpty = Boolean(!value.size); | |
break; | |
} | |
return isEmpty; | |
}; | |
/** | |
* Evaluates the type of data sent, useful with 'array' type data as the typeof | |
* function returns 'object' in this and other cases. | |
* @author EdwinBetanc0urt <EdwinBetanc0urt@oulook.com> | |
* @param {boolean|array|object|number|string|date|map|set|function} value | |
* @returns {string} value type in capital letters (STRING, NUMBER, BOOLEAN, ...) | |
*/ | |
export const typeValue = function(value) { | |
const typeOfValue = Object.prototype | |
.toString | |
.call(value) | |
.match(/^\[object\s(.*)\]$/)[1] | |
.toUpperCase(); | |
return typeOfValue; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment