Skip to content

Commit

Permalink
feat(transform): add mapOrElse transform function
Browse files Browse the repository at this point in the history
  • Loading branch information
TomokiMiyauci committed Jul 4, 2023
1 parent 64acdaa commit cf3fa6e
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
21 changes: 21 additions & 0 deletions operators/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,24 @@ export function mapOr<T, U>(

return defaultValue;
}

/** Computes a default function result (if none), or applies a different function to the contained value (if any).
*
* @example
* ```ts
* import { mapOrElse, Option, Some } from "https://deno.land/x/optio/mod.ts";
* import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
*
* const option: Option<string> = Some.of("Hello");
* assertEquals(mapOrElse(option, () => 2 ** 3, ({ length }) => length), 5);
* ```
*/
export function mapOrElse<T, U>(
option: Option<T>,
defaultFn: () => U,
fn: (value: T) => U,
): U {
if (isSome(option)) return fn(option.get);

return defaultFn();
}
28 changes: 27 additions & 1 deletion operators/transform_test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Copyright © 2023 Tomoki Miyauchi. All rights reserved. MIT license.

import { map, mapOr } from "./transform.ts";
import { map, mapOr, mapOrElse } from "./transform.ts";
import { None, Option, Some } from "../spec.ts";
import {
assertEquals,
Expand Down Expand Up @@ -54,3 +54,29 @@ describe("mapOr", () => {
assertSpyCalls(fn, 0);
});
});

describe("mapOrElse", () => {
it("should call mapper if it is some", () => {
const INPUT = "Hello, World!";
const option: Option<string> = Some.of(INPUT);
const fn = spy((v: string) => v.length);
const defaultFn = spy(() => 0);
const optionLen = mapOrElse(option, defaultFn, fn);

assertEquals(optionLen, INPUT.length);
assertSpyCalls(fn, 1);
assertSpyCallArgs(fn, 0, [INPUT]);
assertSpyCalls(defaultFn, 0);
});

it("should return default value if it is none", () => {
const option: Option<string> = None;
const fn = spy((v: string) => v.length);
const defaultFn = spy(() => 0);
const optionLen = mapOrElse(option, defaultFn, fn);

assertEquals(optionLen, 0);
assertSpyCalls(fn, 0);
assertSpyCalls(defaultFn, 1);
});
});

0 comments on commit cf3fa6e

Please sign in to comment.