Skip to content

Commit

Permalink
add wrapNullish() as an available option
Browse files Browse the repository at this point in the history
  • Loading branch information
tonyboylehub committed Oct 25, 2024
1 parent 4d78f09 commit f6d68a6
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
6 changes: 6 additions & 0 deletions packages/umi-options/src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@
*/
export type Nullable<T> = T | null;

/**
* Defines a type `T` that can also be `null` or `undefined`.
* @category Utils — Options
*/
export type Nullish<T> = T | null | undefined;

/**
* An implementation of the Rust Option type in JavaScript.
* It can be one of the following:
Expand Down
10 changes: 9 additions & 1 deletion packages/umi-options/src/unwrapOption.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Nullable, Option, isSome, none, some } from './common';
import { Nullable, Nullish, Option, isSome, none, some } from './common';

/**
* Unwraps the value of an {@link Option} of type `T`
Expand All @@ -24,6 +24,14 @@ export function unwrapOption<T, U = null>(
export const wrapNullable = <T>(nullable: Nullable<T>): Option<T> =>
nullable !== null ? some(nullable) : none<T>();

/**
* Wraps a nullish value into an {@link Option}.
*
* @category Utils — Options
*/
export const wrapNullish = <T>(nullish: Nullish<T>): Option<T> =>
nullish !== null && nullish !== undefined ? some(nullish) : none<T>();

/**
* Unwraps the value of an {@link Option} of type `T`.
* If the option is a {@link Some}, it returns its value,
Expand Down
11 changes: 10 additions & 1 deletion packages/umi-options/test/unwrapOption.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import test from 'ava';
import { none, some, unwrapOption, wrapNullable } from '../src';
import { none, some, unwrapOption, wrapNullable, wrapNullish } from '../src';

test('it can unwrap an Option as a Nullable', (t) => {
t.is(unwrapOption(some(42)), 42);
Expand Down Expand Up @@ -34,3 +34,12 @@ test('it can wrap a Nullable as an Option', (t) => {
t.deepEqual(wrapNullable<string>(null), none<string>());
t.deepEqual(wrapNullable<number>(null), none<number>());
});

test('it can wrap a Nullish as an Option', (t) => {
t.deepEqual(wrapNullish(42), some(42));
t.deepEqual(wrapNullish('hello'), some('hello'));
t.deepEqual(wrapNullish(false), some(false));
t.deepEqual(wrapNullish(undefined), none<undefined>());
t.deepEqual(wrapNullish<string>(null), none<string>());
t.deepEqual(wrapNullish<number>(null), none<number>());
});

0 comments on commit f6d68a6

Please sign in to comment.