Len
Is a function that returns the length of a value. The function is inspired from Python len function.
๐ฌ Usage
<script>
import {len} from "@sveu/shared"
const value = "Hello World"
</script>
<h1>Length of "{value}" is {len(value)}</h1>
๐ฉโ๐ปAPI
๐ป Arguments
Name | Description | Type | Required |
---|---|---|---|
item | The value to get the length from. | any | Yes |
โฉ๏ธ Returns
The length of the value. It will throw an error if the value is not iterable.
๐งช Playground
Source Code ๐
Source Code
import { type } from "../type"
/**
* 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
*
* @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)}`
)
}
Last update: 2023-02-09
Authors: Mohamed-Kaizen