JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 999
  • Score
    100M100P100Q96938F
  • License Apache-2.0

Ensures that a number is within the natural numbers (0, 1, 2...) or throws a RangeError

Package Exports

  • @agoric/nat

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@agoric/nat) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Nat

Build Status dependency status dev dependency status License

Nat(value) returns its argument if it represents a non-negative integer (i.e. a "natural number") that can be accurately represented as a JavaScript BigInt, a built-in object that can be used to represent arbitrarily large integers. If the argument is not a BigInt or the argument is negative, an exception is thrown. This makes it easy to use Nat() on incoming arguments, or as an assertion on generated values.

You can think of Nat() as a type enforcement.

How to use

Nat() can be used to enforce desired properties on account balances, where precision is important.

For instance, in a deposit scenario, you would want to defend against someone "depositing" a negative value. Use Nat to validate the amount to be deposited before proceeding:

deposit: function(amount) {
  amount = Nat(amount);
  ...
}

Any addition or subtraction expressions dealing with monetary amounts should protected with Nat() to guard against overflow/underflow errors. Without this check, the two balances might both be safe, but their sum might be too large to represent accurately, causing precision errors in subsequent computation:

Nat(myOldBal + amount);
const srcNewBal = Nat(srcOldBal - amount);

Non-monetary usage

Array indexes can be wrapped with Nat(), to guard against the surprising string coercion of non-integral index values:

const a = [2,4,6]
function add(index, value) {
  a[Nat(index)] = value;
}
add(3, 8); // works
add(2.5, 7); // throws rather than add a key named "2.5"

Nat can be used even in cases where it is not strictly necessary, for extra protection against human error.

Bounds

Because Nat uses JavaScript's upcoming BigInt standard, the range of accurately-representable integers is effectively unbounded.

History

Nat comes from the Google Caja project, which tested whether a number was a primitive integer within the range of continguously representable non-negative integers.

For more, see the discussion in TC39 notes