-
Notifications
You must be signed in to change notification settings - Fork 3
/
len.ts
26 lines (24 loc) · 813 Bytes
/
len.ts
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
import { isArrayLike } from './is-array-like'
import { isMap } from './is-map'
import { isObject } from './is-object'
import { isSet } from './is-set'
import { isString } from './is-string'
import { isFunction } from './is-function'
import { isNumber } from './is-number'
/**
* Get length of element
*
* Works for array, object, string, set, map, and function
* @example
* len('foo') // => 3
* len([ 1, 2 ]) => 2
* len((a, b) => a + b) // => 2
*/
export const len = (val: any): number => {
if (isNumber(val)) return val
if (Array.isArray(val) || isString(val) || isFunction(val) || isArrayLike(val)) return val.length
if (isMap(val) || isSet(val)) return val.size
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
if (isObject(val)) return Object.keys(val).length
return 0
}