ts-data-forge
    Preparing search index...
    • Applies a function that returns a Result to the success value of a Result. If the input is Err, returns the original Err. This is the monadic bind operation for Result.

      Type Parameters

      • R extends Result.Base

        The input Result.Base type.

      • S2

        The success type of the Result returned by the function.

      • E2

        The error type of the Result returned by the function.

      Parameters

      • result: R

        The Result to flat map.

      • flatMapFn: (value: UnwrapOk<R>) => Result<S2, E2>

        The function to apply that returns a Result.

      Returns Result<S2, E2 | UnwrapErr<R>>

      The result of applying the function, or the original Err.

      const parseNumber = (input: string): Result<number, string> => {
      const num = Number.parseInt(input, 10);
      return Number.isNaN(num) ? Result.err('not a number') : Result.ok(num);
      };

      const parsed = Result.flatMap(Result.ok('42'), parseNumber);
      const failure = Result.flatMap(Result.ok('abc'), parseNumber);
      const passthrough = Result.flatMap(Result.err('fail'), parseNumber);

      assert.deepStrictEqual(parsed, Result.ok(42));
      assert.deepStrictEqual(failure, Result.err('not a number'));
      assert.deepStrictEqual(passthrough, Result.err('fail'));

      const parseThenDouble = Result.flatMap((input: string) =>
      Result.map(parseNumber(input), (value) => value * 2),
      );

      assert.deepStrictEqual(parseThenDouble(Result.ok('10')), Result.ok(20));
    • Applies a function that returns a Result to the success value of a Result. If the input is Err, returns the original Err. This is the monadic bind operation for Result.

      Type Parameters

      • S
      • S2

        The success type of the Result returned by the function.

      • E2

        The error type of the Result returned by the function.

      Parameters

      • flatMapFn: (value: S) => Result<S2, E2>

        The function to apply that returns a Result.

      Returns <E>(result: Result<S, E>) => Result<S2, E2 | E>

      The result of applying the function, or the original Err.

      const parseNumber = (input: string): Result<number, string> => {
      const num = Number.parseInt(input, 10);
      return Number.isNaN(num) ? Result.err('not a number') : Result.ok(num);
      };

      const parsed = Result.flatMap(Result.ok('42'), parseNumber);
      const failure = Result.flatMap(Result.ok('abc'), parseNumber);
      const passthrough = Result.flatMap(Result.err('fail'), parseNumber);

      assert.deepStrictEqual(parsed, Result.ok(42));
      assert.deepStrictEqual(failure, Result.err('not a number'));
      assert.deepStrictEqual(passthrough, Result.err('fail'));

      const parseThenDouble = Result.flatMap((input: string) =>
      Result.map(parseNumber(input), (value) => value * 2),
      );

      assert.deepStrictEqual(parseThenDouble(Result.ok('10')), Result.ok(20));