Saturday, October 27, 2018

lodash - Validating a non-empty String in Lo-Dash

[Use-case: portable Lo-Dash code]
I've been looking for an elegant Lo-Dash empty-string validator in our nodeJS projects for some time now, because _.isEmpty() only handles Arrays and Objects. So I always ended up doing it with the ugly old-fashioned likes of:



if (typeof(myString) !== "undefined" && myString.trim() !== "") {
// handle the string
}



... Until I stumbled upon _.toString(), which returns '' for null and undefined. So I created a mixin in our extendedLodash.js helper that uses only Lo-Dash methods. However I'm uncertain of caveats; any comment on what I might be overseeing is welcome:



'use strict';

const _ = require('lodash');

/**
* Extension of _.isEmpty(), which will return `true` for
* "", 0, [], {}, false, undefined and null
* @param stringOrObjectOrNull

* @returns {boolean}
*/
function empty(stringOrObjectOrNull) {
return _(stringOrObjectOrNull).toString().trim() === ""
|| _.isEmpty(stringOrObjectOrNull);
}

_.mixin({
empty
});


module.exports = _;


Now we can use this:



const _ = require('../lib/helpers/extendedLodash'); 
if (!_.empty(myStringOrObject)) {
// handle the string ( ...or object ;-| )
}



And test:



  console.log('is empty `[]`: ' + _.empty([]) + " -> " + "`" + _.toString([]) + "`");
console.log('is empty `{}`: ' + _.empty({}) + " -> " + "`" + _.toString({}) + "`");
console.log('is empty `""`: ' + _.empty("") + " -> " + "`" + _.toString("") + "`");
console.log('is empty `" "`: ' + _.empty(" ") + " -> " + "`" + _.toString(" ") + "`");
console.log('is empty `0`: ' + _.empty(0) + " -> " + "`" + _.toString(0) + "`");
console.log('is empty `false`: ' + _.empty(false) + " -> " + "`" + _.toString(false) + "`");

console.log('is empty `null`: ' + _.empty(null) + " -> " + "`" + _.toString(null) + "`");
console.log('is empty `undefined`: ' + _.empty(undefined) + " -> " + "`" + _.toString(undefined) + "`");


Note: Going over this code again, I realize this behaves just as fuzzy as PHP's empty() method ... I'm not sure that is appropriate; I just want to avoid necessity of catching undefined where variables might not be declared (...)

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...