📏 Returns the size (length, count, or byte length) of a collection.

Info

The following types are supported:

  • String: Number of characters.

  • Array: Number of elements.

  • Plain Object: Number of enumerable own string-keyed and symbol-keyed properties.

  • Map & Set: Number of entries.

  • ArrayBuffer, TypedArray, & DataView: Byte length or number of elements.

Warning

Returns -1 if the value is an unsupported type (e.g., null, undefined, number, boolean).

Syntax

TypeScript
import { size } from '@opentf/std';

size(val: unknown): number

Parameters

  • val: The value to measure.

Returns

The size of the collection, or -1 if unsupported.

Examples

TypeScript
// --- Strings ---
size('') //=> 0
size('abc') //=> 3

// --- Arrays ---
size([]) //=> 0
size([1, 2, 3]) //=> 3

// --- Objects ---
size({}) //=> 0
size({ a: 1, b: 2 }) //=> 2
size({ [Symbol('x')]: 1 }) //=> 1

// --- Maps & Sets ---
size(new Map([['a', 1]])) //=> 1
size(new Set([1, 2])) //=> 2

// --- Buffers ---
size(new ArrayBuffer(8)) //=> 8
size(new Uint8Array(10)) //=> 10

// --- Unsupported ---
size(null) //=> -1
size(123) //=> -1
Last updated on
Edit this page