From 5a5856be545754a61a9ed36bf451de4d5261fda4 Mon Sep 17 00:00:00 2001 From: Aitor Santana Date: Tue, 12 Nov 2024 10:35:50 +0000 Subject: [PATCH] feat(Option): :sparkles: Add new methods for Option --- src/option/option.test.ts | 8 ++++++++ src/option/option.ts | 26 +++++++++++++++++++++++++- src/types.ts | 1 + tsconfig.json | 4 +++- 4 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/option/option.test.ts b/src/option/option.test.ts index 336ef06..0899fda 100644 --- a/src/option/option.test.ts +++ b/src/option/option.test.ts @@ -49,4 +49,12 @@ describe('Option monad', () => { ])('$type should handle isSome operation correctly', ({ option, expected }) => { expect(option.isSome()).toEqual(expected); }); + + it('should create a Some', () => { + expect(Option.some(2)).toEqual(new Some(2)); + }); + + it('should create a None', () => { + expect(Option.none()).toEqual(new None()); + }); }); diff --git a/src/option/option.ts b/src/option/option.ts index 076836e..e997286 100644 --- a/src/option/option.ts +++ b/src/option/option.ts @@ -1,4 +1,4 @@ -import { Nullable } from '../types'; +import { Present, Nullable } from '../types'; import { Monad } from '../monad'; import { Matchable } from '../match'; @@ -26,6 +26,30 @@ abstract class Option implements Monad, Matchable { return new Some(value); } + /** + * Creates an `Option` instance from a value. + * @template T The type of the value. + * @param {Present} value The nullable value. + * @returns {Some} A `Some` instance of the value + * @example + * const some = Option.some(5); + * some.match(console.log, () => console.log('none')); // 5 + */ + static some(value: Present): Option { + return new Some(value); + } + + /** + * Creates a `None` instance. + * @returns {None} A `None` instance. + * @example + * const none = Option.none(); + * none.match(console.log, () => console.log('none')); // none + */ + static none(): Option { + return new None(); + } + /** * Creates an `Option` instance from a `Matchable` instance. * @template T The type of the value. diff --git a/src/types.ts b/src/types.ts index 164a705..31161a2 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1 +1,2 @@ export type Nullable = T | null | undefined; +export type Present = Exclude; diff --git a/tsconfig.json b/tsconfig.json index e4e6cd5..231fa54 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -9,7 +9,9 @@ "moduleResolution": "node", "esModuleInterop": true, "skipLibCheck": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "strict": true, + "strictNullChecks": true, }, "include": ["src"], "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"]