§ Quick Take

import { strict as assert } from "assert";
import { nonEmpty } from "util-nonempty";

assert.equal(nonEmpty("z"), true);
assert.equal(nonEmpty(""), false);
assert.equal(nonEmpty(["a"]), true);
assert.equal(nonEmpty([123]), true);
assert.equal(nonEmpty([[[[[[[[[[[]]]]]]]]]]]), true);
assert.equal(nonEmpty({ a: "" }), true);
assert.equal(nonEmpty({ a: "a" }), true);
assert.equal(nonEmpty({}), false);

const f = () => {
  return "z";
};
assert.equal(nonEmpty(f), false);
// (answer is instantly false if input is not array, plain object or string)

§ Purpose

It is a quick utility function, to be able to detect is the input not empty.

  • null, unefined yields false
  • any number (incl. zero) yields true
  • any array or string with length > 0 yields true, otherwise false
  • plain objects with at least one key yields true, otherwise false
  • all other types yield false

If you want to check non-emptiness of complex nested trees of objects, arrays and strings (like parsed HTML AST), you need a library which can recursively traverse that. There are two options:

  • If you want to check for strict emptiness, that is [] or {} is empty, but {aaa: ' \n\n\n ', ' \t'} is not, see ast-is-empty
  • If your "emptiness" definition is "everything that String.trim()'s to an empty string'" (this includes tabs, spaces and line breaks for example, but not letters), see ast-contains-only-empty-space, or plain objects without keys or zero-length arrays.

§ API

nonEmpty(something)

It's a function: anything-in, boolean-out.

§ Changelog

See it in the monorepo opens in a new tab, on GitHub.

§ Contributing

To report bugs or request features or assistance, raise an issue on GitHub opens in a new tab.

Any code contributions welcome! All Pull Requests will be dealt promptly.

§ Licence

MIT opens in a new tab

Copyright © 2010–2021 Roy Revelt and other contributors

Related packages:

📦 util-array-object-or-both 3.0.14
Validate and normalise user choice: array, object or both?