Last active
February 20, 2023 19:19
-
-
Save DaveyJake/2096f3f7b09d26fcce25c1886e2571a0 to your computer and use it in GitHub Desktop.
PHP `empty` Function Using Lodash
This file contains hidden or 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
/** | |
* Lodash version of PHP's `empty` function. | |
* | |
* @author Davey Jacobson <daveyjake21 [at] geemail [dot] com> | |
* @since 1.0.0 Initial private gist. | |
* @since 1.1.0 Gist made public. | |
* @since 1.1.1 Additional checks for 'null' and 'undefined' as strings. | |
* @since 1.1.2 Additional check for `NaN` and 'NaN' as a string. | |
* | |
* @param {array|bool|number|object|string} $value The value to check. | |
* | |
* @return {bool} True if `value` is one of the conditions. False if not. | |
*/ | |
function empty( $value ) { | |
/** | |
* Conditions we want to return as true. | |
* | |
* @since 1.0.0 | |
* @since 1.1.1 Added checks for 'null' and 'undefined'. | |
* @since 1.1.2 Added check for `NaN` and 'NaN'. | |
* | |
* @type array | |
*/ | |
let conditions = [ | |
_.isEqual( $value, 0 ), | |
_.isEqual( $value, '0' ), | |
_.isEqual( $value, false ), | |
_.isEqual( $value, 'false' ), | |
_.isEqual( $value, '' ), | |
_.isEqual( $value, [] ), | |
_.isEqual( $value, {} ), | |
_.isEqual( _.isNaN( $value ), true ), | |
_.isEqual( $value, 'NaN' ), | |
_.isEqual( _.isNull( $value ), true ), | |
_.isEqual( $value, 'null' ), | |
_.isEqual( _.isUndefined( $value ), true ), | |
_.isEqual( $value, 'undefined' ) | |
]; | |
// Convert boolean results to integers: true = 1; false = 0. | |
conditions = _.map( conditions, _.toNumber ); | |
// Get the sum of the results. | |
const result = _.reduce( conditions, ( a, b ) => { | |
return a + b; | |
}); | |
// If the result is greater than 0, we know it's empty. | |
if ( result > 0 ) { | |
return true; | |
} | |
return false; | |
} | |
// Add to Lodash object (i.e. make `_.empty` a usable function). | |
_.mixin({ 'empty': empty }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment