All files / src/mixin optional.ts

35.48% Statements 11/31
42.85% Branches 3/7
15.38% Functions 2/13
36.66% Lines 11/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273                              2x                                                                                                                                                                                                                                                                                                       1x 2x                                                 2x       2x       2x 2x           2x     2x 2x             2x                                                                                                                  
import { makeFluent } from "../base";
import type { HKT } from "../base/hkt";
import {
	Mixin,
	type Input,
	type Props,
	type Return,
} from "../base/mixin";
import { assert, assertType, type HidePrototype } from "../internal";
 
type NoneSentinel = null | undefined;
type None<T> = Extract<T, NoneSentinel>;
type Some<T> = Exclude<T, NoneSentinel>;
 
function isNone<T>(v: T): v is None<T> {
	return v === null || v === undefined;
}
 
interface Where<T, t extends Props> {
	/**
	 * Set a value to a fallback if it does not conform to some conditional
	 * @param callback Callback returning a boolean, `false` sets the value to the fallback
	 * @param fallback The fallback value, `null` by default
	 * @example
	 * const parse = () => { version: "1.2.4" } as unknown;
	 *
	 * const version = $(parse())
	 *  .where(v => typeof v === 'object' &&
	 *      v !== null &&
	 *      'version' in v)
	 *  .and(v => v.version)
	 *  .or("1.0.0")
	 *  .value;
	 * expect(version).toBe("1.2.4");
	 * @from {@link Optional `Optional`}
	 */
	where: <U = null>(
		callback: (v: T) => boolean,
		fallback?: U,
	) => Return<T | U, t>;
}
 
export interface Optional extends Mixin.HKT {
	new: (t: HKT.T<this>) => Input<typeof t> extends infer T
		? None<T> extends never
			? Where<T, typeof t>
			: {
					/**
					 * Transform a value via callback if it is not `null` or
					 * `undefined`
					 *
					 * If the value is equal to `null` or `undefined`, it
					 * remains unchanged and the callback is not called.
					 * @param callback Function for a non-null value
					 * @example
					 * const none = () => null as number | null;
					 * const some = () => 10 as number | null;
					 *
					 * const callback = (v: number) => v + 5;
					 *
					 * const a = $(none()).and(callback).value;
					 * expect(a).toBe(null)
					 *
					 * const b = $(some()).and(callback).value;
					 * expect(b).toBe(15);
					 * @from {@link Optional `Optional`}
					 */
					and: <U>(
						callback: (v: Some<T>) => U,
					) => Return<None<T> | U, typeof t>;
					/**
					 * Set value to a fallback if it is `null` or `undefined`.
					 * @param fallback The fallback value to use. To defer
					 * computing this fallback value, you can use `.or.else()`
					 * @example
					 * const none = () => null as number | null;
					 * const some = () => 10 as number | null;
					 *
					 * const fallback = -1;
					 *
					 * const a = $(none()).or(fallback).value;
					 * expect(a).toBe(fallback);
					 *
					 * const b = $(some()).or(fallback).value;
					 * expect(b).toBe(10);
					 * @from {@link Optional `Optional`}
					 */
					or: (<const U>(
						fallback: U,
					) => Return<Some<T> | U, typeof t>) & {
						/**
						 * Set value to the result of `callback` if it is `null`
						 * or `undefined`. Unlike the normal `.or()`, this method
						 * only computes the fallback if the value is `null` or
						 * `undefined`
						 * @param callback
						 * @from {@link Optional `Optional`}
						 * @example
						 * ```ts
						 * const none = () => null as number | null;
						 * const some = () => 8 as number | null;
						 *
						 * const fallback = vi.fn(() => 22); // mocked
						 *
						 * const a = $(none()).or.else(fallback).value;
						 * expect(a).toBe(22);
						 *
						 * const b = $(some()).or.else(fallback).value;
						 * expect(b).toBe(8);
						 *
						 * expect(fallback).toHaveBeenCalledOnce()
						 * ```
						 */
						else: <U>(
							callback: (v: None<T>) => U,
						) => Return<Some<T> | U, typeof t>;
					} & HidePrototype;
					/**
					 * Assert that value is not `null` or `undefined`
					 * @param msg Reasoning to attach to the `AssertionError`
					 * @see `.assert.none()` for the inverse assertion
					 * @from {@link Optional `Optional`}
					 * @example
					 * ```ts
					 * const array = [1, 2, 3];
					 * const element: number | undefined = array[1];
					 *
					 * const v = $(element).assert("index within bounds").value;
					 * expect(v).toBe(2);
					 *
					 * expect(() => {
					 *  $(array[6]).assert()
					 * }).toThrow()
					 * ```
					 */
					assert: ((
						msg?: string,
					) => Return<Some<T>, typeof t>) & {
						/**
						 * Assert that the value is either `null` or `undefined`
						 * @param msg Reasoning to attach to the `AssertionError`
						 * @from {@link Optional `Optional`}
						 * @example
						 * ```ts
						 * const array = [1, 2, 3];
						 * const element: number | undefined = array[5];
						 *
						 * const v = $(element).assert.none("index out of bounds").value;
						 * expect(v).toBe(undefined);
						 *
						 * expect(() => {
						 *  $(array[1]).assert.none()
						 * }).toThrow()
						 * ```
						 */
						none: (
							msg?: string,
						) => Return<None<T>, typeof t>;
					} & HidePrototype;
				} & Where<T, typeof t>
		: never;
}
 
export const Optional = Mixin<Optional>((value, $, fluent) => {
	Iif (isNone(value)) {
		$.and = () => {
			return fluent(value);
		};
 
		$.or = (fallback: unknown) => {
			return fluent(fallback);
		};
		assertType<object>($.or);
		Object.assign($.or, {
			else: (callback: (v: unknown) => unknown) => {
				return fluent(callback(value));
			},
		});
 
		$.assert = (msg?: string) => {
			assert(false, msg);
		};
		assertType<object>($.assert);
		Object.assign($.assert, {
			none: () => {
				return fluent(value);
			},
		});
	} else {
		$.and = (callback: (v: unknown) => unknown) => {
			return fluent(callback(value));
		};
 
		$.or = () => {
			return fluent(value);
		};
 
		assertType<object>($.or);
		Object.assign($.or, {
			else: () => {
				return fluent(value);
			},
		});
 
		$.assert = () => {
			return fluent(value);
		};
		assertType<object>($.assert);
		Object.assign($.assert, {
			none: (msg?: string) => {
				assert(false, msg);
			},
		});
	}
 
	$.where = (
		callback: (v: unknown) => boolean,
		fallback = null,
	) => {
		if (callback(value)) return fluent(value);
		return fluent(fallback);
	};
});
 
if (import.meta.vitest) {
	const { test, expect, vi } = import.meta.vitest;
 
	const registry = [Optional] as const;
	const $ = makeFluent(registry);
 
	type Value = number | null;
 
	test("and()", () => {
		const value = 10;
		const some = value as Value;
		const none = null as Value;
 
		const callback = (v: number) => v + 5;
 
		expect($(some).and(callback).value).toBe(callback(value));
		expect($(none).and(callback).value).toBe(null);
	});
 
	test("or()", () => {
		const some = 10 as Value;
		const none = null as Value;
 
		const fallback = 15 as const;
 
		expect($(some).or(fallback).value).toBe(some);
		expect($(none).or(fallback).value).toBe(fallback);
 
		const callback = vi.fn(() => fallback);
 
		expect($(some).or.else(callback).value).toBe(some);
		expect($(none).or.else(callback).value).toBe(fallback);
 
		expect(callback).toHaveBeenCalledOnce();
	});
 
	test("where()", () => {
		const even = 4;
		const odd = 7;
 
		const isEven = (v: number) => v % 2 === 0;
 
		expect($(even).where(isEven).value).toBe(even);
		expect($(odd).where(isEven).value).toBe(null);
 
		expect($(odd).where(isEven, -1).value).toBe(-1);
	});
}