验证Lo-Dash中的非空字符串

时间:2018-04-10 20:36:47

标签: lodash

[用例:便携式Lo-Dash代码] 我一直在寻找一个优雅的Lo-Dash空字符串验证器,因为_.isEmpty()只处理数组和对象。因此,我最终总是以丑陋的老式喜欢这样做:

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

...直到我偶然发现_.toString()''null返回undefined。所以我在我们的extendedLodash.js帮助器中创建了一个mixin,它只使用了Lo-Dash方法。但是我不确定是否有警告; 欢迎任何关于我可能会监督的评论

'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 = _;

现在我们可以使用它:

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

并测试:

  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) + "`");

注意:再次查看此代码,我意识到这与PHP的empty()方法一样模糊......我不确定这是否合适;我只想避免必须捕获undefined,其中变量可能未被声明(...)

0 个答案:

没有答案