Skip to Content
  • Website
Codsen
  • Home
  • Open Source
  • Articles
  • About

prevOpen Source→ast-is-emptynext

ast-is-empty4.2.4

Find out, is nested array/object/string/AST tree is empty

Downloads per monthChangelogMIT Licenselibera manifesto
  • the top
  • Installation
  • Quick Take
  • Examples
  • PURPOSE
  • API — ISEMPTY()
  • STRICT STRING…
  • SUPPORTED VA…
  • ARRAYS AND OB…
  • OPTIONS
  • PROGRESS AND…
  • INVALID OPTIO…
  • API — DEFAULTS
  • TYPES
  • API — VERSION
  • Changelog

No 3rd party dependencies. All dependencies and devDependencies, checked recursively, are Codsen packages.

Permalink to InstallationInstallation

Permalink to Quick TakeQuick Take

Permalink to ExamplesExamples

  • Terminate on cycles and reuse completed shared subtrees
  • Recognise a tree made only from empty strings and containers
  • Inspect frozen completion statistics
  • Compose progress reporting into a caller's range
  • Return null when the tree contains an unsupported value type
  • Treat whitespace-only strings as content

Purpose

This package checks whether a string or a recursively nested array/plain-object tree is strictly empty. It is useful when an abstract syntax tree must contain no text at all—not even whitespace.

API — isEmpty()

The main function isEmpty() is imported like this:

The function takes a value and an optional reporting-options object:

Input argumentTypeRequiredDescription
input
Type: unknown
inputunknownyesThe value to inspect.
opts
Type: InputOpts, null, or undefined
optsInputOpts, null, or undefinednoProgress and completion options. null and undefined use the published defaults.

The return value has three states:

  • true means every inspected string has zero code units and every inspected container is empty or contains only empty supported values;
  • false means the fully supported tree contains at least one non-empty string; and
  • null means the tree contains an unsupported value, a sparse array hole, or a cycle.

null takes precedence over false. A tree containing both known text and an unsupported value therefore returns null, regardless of sibling order or object-key insertion order. The function does not mutate its input.

isEmpty({ title: "", children: ["", {}] });
// => true

isEmpty({ title: " " });
// => false

isEmpty({ title: "visible", count: 0 });
// => null

Strict strings

Only a zero-length primitive string is empty. The function does not trim its input, so spaces, tabs, and line breaks are content:

isEmpty("");
// => true

isEmpty(" \n\t");
// => false

Supported values

The recursive input grammar consists of primitive strings, native arrays, and plain objects. Empty arrays and plain objects return true.

Every other reached leaf is unsupported and makes the result null. This includes numbers, booleans, bigints, null, undefined, symbols, functions, boxed primitives, Date, RegExp, Map, Set, and class instances. Accepting an unknown TypeScript input means the function can classify these values; it does not mean they are valid members of the supported tree grammar.

Arrays and objects

Arrays are inspected through their own indexed slots. The function does not invoke the array’s iterator, so replacing, deleting, or poisoning Symbol.iterator does not change the result. A sparse hole returns null, and an inherited numeric property does not fill it. Non-index string properties and symbol properties on an array are ignored.

Plain objects contribute their own enumerable string-keyed properties. Symbol and non-enumerable properties are ignored. Null-prototype and cross-realm records are supported.

Traversal uses bounded call-stack space and handles deeply nested input. A direct or indirect cycle returns null. When several paths refer to the same completed array or object, the shared container is inspected only once.

Options

KeyTypeDefaultDescription
reportCompletionFunc
Type: Function or null
Default: null
reportCompletionFuncFunction or nullnullReceives frozen completion statistics after the tri-state result is known.
reportProgressFunc
Type: Function or null
Default: null
reportProgressFuncFunction or nullnullReceives finite, monotonic progress values during traversal.
reportProgressFuncFrom
Type: Finite number
Default: 0
reportProgressFuncFromFinite number0Sets the first value in the composable progress range.
reportProgressFuncTo
Type: Finite number
Default: 100
reportProgressFuncToFinite number100Sets the final value. It cannot be lower than the start, and the span must remain finite.

The exported defaults object is frozen. Passing explicit undefined for an option uses its default value.

Progress and completion reports

reportProgressFunc receives the configured start value, sampled monotonic intermediate values for sufficiently large traversals, and the configured end value. Use reportProgressFuncFrom and reportProgressFuncTo when this scan is one stage of a wider operation.

reportCompletionFunc runs once after the result is known, including false and null results. It receives these frozen statistics:

KeyDescription
aliasesSkipped
aliasesSkippedLinks to already-completed shared containers that did not need another traversal.
arrayElementsVisited
arrayElementsVisitedArray indices inspected, including a sparse hole that determines the result.
maxDepth
maxDepthDeepest value or array slot inspected. The root has depth 0.
objectPropertiesVisited
objectPropertiesVisitedOwn enumerable string-keyed object properties inspected.
timeTakenInMilliseconds
timeTakenInMillisecondsBest-effort, finite, non-negative elapsed time.
uniqueContainersVisited
uniqueContainersVisitedDistinct arrays and plain objects entered.

Exceptions thrown by either callback are ignored. Callbacks run synchronously during traversal; do not mutate the input from a callback because later reads observe those mutations. Clock failures and unusable clock differences do not affect the result; unavailable elapsed time is reported as 0.

const progress = [];
let completion;

const result = isEmpty(["", { value: "" }], {
  reportProgressFunc(percentageDone) {
    progress.push(percentageDone);
  },
  reportProgressFuncFrom: 20,
  reportProgressFuncTo: 80,
  reportCompletionFunc(stats) {
    completion = stats;
  },
});

// result === true
// progress[0] === 20
// progress[progress.length - 1] === 80
// completion.uniqueContainersVisited === 2

Invalid options

The options argument must be a plain object, null, or undefined. Unknown own enumerable string-keyed option properties, invalid callbacks, non-finite range endpoints, a start greater than the end, and an overflowing range span throw a package-owned TypeError or RangeError. Each message starts with ast-is-empty/isEmpty(): [THROW_ID_XX].

API — defaults

You can import defaults:

It's a plain object:

The main function calculates the options to be used by merging the options you passed with these defaults.

Types

This TypeScript package exports CompletionStats, InputOpts, and Opts:

import type { CompletionStats, InputOpts, Opts } from "ast-is-empty";

API — version

You can import version:

Permalink to changelogChangelog

Open Changelog
↑ back to top
prev next

Copyright

All rights reserved © Roy Revelt 2026
All our open source packages are under MIT licenceopens in a new tab

Activities

🐛 See a bug? Raise an issueopens in a new tab
💘 Check out the Indiewebopens in a new tab and Libera manifestoopens in a new tab