MikeMcl / big.js

A small, fast JavaScript library for arbitrary-precision decimal arithmetic.

Home Page:http://mikemcl.github.io/big.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add a `Big.nullable(value)` method

sparebytes opened this issue · comments

I appreciate that Big(x) throws when x is null/undefined but there are times I know I'm working with a value that may be nullable and want to fail gracefully. Big.nullable(value) makes it a bit easier to work with javascript's new null coalescing and optional chaining operators.

// simple case - not a huge benefit
return x == null ? Big(x).toFixed(2) : "Not set"
return Big.nullable(x)?.toFixed(2) ?? "Not set

// with optional chaining
return data?.user.rating == null ? Big.nullable(data.user.rating) .toFixed(2): "N/A";
return Big.nullable(data?.user.rating)?.toFixed(2) ?? "N/A";

See also #32

If I am understanding you correctly, then the implementation would just be

Big.nullable = x => x == null ? x : Big(x);

Yes?

The typescript def would look something like this

interface Big {
  nullable(value: BigSource): Big;
  nullable(value: null): null;
  nullable(value: undefined): undefined;
}

Edit: I lied, Typescript won't spread the overloads as I thought.

interface Big {
  nullable(value: BigSource | null | undefined): Big | null | undefined;
}