-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
42 lines (36 loc) · 996 Bytes
/
index.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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { type } from "../utils"
/**
* A function that returns the length of an item.
*
* @param item - The item to get the length of.
*
* @see https://docs.python.org/3/library/functions.html#len
*
* @example
* ```ts
* len([1, 2, 3]) // 3
*
* len("hello") // 5
*
* len({ a: 1, b: 2 }) // 2
*
* len(new Set([1, 2, 3])) // 3
*
* len(new Map([["a", 1], ["b", 2]])) // 2
*
* len(1) // TypeError: len() argument must be a sequence or collection, not number
*
* len(null) // TypeError: len() argument must be a sequence or collection, not null
* ```
* @returns The length of the item.
*/
export function len<T>(item: T): number {
if (item instanceof Map) return item.size
if (item instanceof Set) return item.size
if (item instanceof Object) return Object.keys(item).length
if (item instanceof Array) return item.length
if (typeof item === "string") return item.length
throw new TypeError(
`len() argument must be a sequence or collection, not ${type(item)}`
)
}