Created
November 16, 2020 10:31
-
-
Save samermurad/05f1d143cb347f2a62e66f9bbffc72d6 to your computer and use it in GitHub Desktop.
lodash getNonNull
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
const _ = require('lodash'); | |
/** | |
* File adds a "getNonNull" function to the set of the lodash functions | |
* function works exactly like `_.get` with one simple exception | |
* the _.getNonNull returns the default value for null values as well | |
* just make sure to require this file on your main js/ts file | |
* | |
* Example: | |
* var foo = { bar: undefined: bar1: null } | |
* with _.get: | |
* _.get(foo, 'bar', 'default') // "default" | |
* _.get(foo, 'bar1', 'default') // null | |
* with _.getNonNull: | |
* _.getNonNull(foo, 'bar', 'default') // "default" | |
* _.getNonNull(foo, 'bar1', 'default') // "default" | |
*/ | |
// eslint-disable-next-line no-prototype-builtins | |
if (!_.hasOwnProperty('getNonNull')) { | |
_.getNonNull = function getNonNull(object, path, defaultValue): any { | |
// eslint-disable-next-line no-useless-call | |
return _.get.apply(_, [object, path, defaultValue]) || defaultValue; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment