前端analysis | 3w & 1h

《Lodash源码阅读笔记》- isEmpty

2020-01-20

isEmpty,用于判断传入值,是否为空对象、空集合([],map,set).
判断依据的标准为:

  • 没有可迭代的字符串键
  • array,str 等参数的 length < 1
  • map,set 类 ,size < 1.
  • 其余的一律认为空,譬如true

源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* isEmpty(null)
* // => true
*
* isEmpty(true)
* // => true
*
* isEmpty(1)
* // => true
*
* isEmpty([1, 2, 3])
* // => false
*
* isEmpty('abc')
* // => false
*
* isEmpty({ 'a': 1 })
* // => false
*/
function isEmpty(value) {
if (value == null) {
return true
}
//类数组、str、buffer、arguments
if (isArrayLike(value) &&
(Array.isArray(value) || typeof value === 'string' || typeof value.splice === 'function' ||
isBuffer(value) || isTypedArray(value) || isArguments(value))) {
return !value.length
}
//set,map
const tag = getTag(value)
if (tag == '[object Map]' || tag == '[object Set]') {
return !value.size
}
//对象
if (isPrototype(value)) {
return !Object.keys(value).length
}
for (const key in value) {
if (hasOwnProperty.call(value, key)) {
return false
}
}
return true
}

export default isEmpty

getTag源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const toString = Object.prototype.toString

/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function getTag(value) {
if (value == null) {
return value === undefined ? '[object Undefined]' : '[object Null]'
}
return toString.call(value) //这个写法,值得学习
}

export default getTag

isPrototype 源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/** Used for built-in method references. */
const objectProto = Object.prototype

/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
const Ctor = value && value.constructor
const proto = (typeof Ctor === 'function' && Ctor.prototype) || objectProto

return value === proto
}

export default isPrototype

isArguments源码

1
2
3
4
5
function isArguments(value) {
return isObjectLike(value) && getTag(value) == '[object Arguments]'
}

export default isArguments

分析其中写法缘由

使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏