db620d33df
CodeQL / Analyze (csharp) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
dotnet-build-and-test / dotnet-test-functions (push) Has been cancelled
dotnet-build-and-test / paths-filter (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Debug, windows-latest, net9.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net8.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-foundry-hosted-it (push) Has been cancelled
dotnet-build-and-test / dotnet-build-and-test-check (push) Has been cancelled
dotnet-build-and-test / Integration Test Report (push) Has been cancelled
37 lines
1.3 KiB
C#
37 lines
1.3 KiB
C#
// Copyright (c) Microsoft. All rights reserved.
|
|
|
|
namespace Harness.ConsoleReactiveFramework;
|
|
|
|
/// <summary>
|
|
/// Caches the result of a mapping function and only recomputes when the input changes.
|
|
/// </summary>
|
|
/// <typeparam name="TInput">The type of the input value.</typeparam>
|
|
/// <typeparam name="TOutput">The type of the mapped output value.</typeparam>
|
|
public class ConsoleReactiveMemo<TInput, TOutput>
|
|
{
|
|
private TInput? _previousInput;
|
|
private TOutput? _cachedOutput;
|
|
private bool _hasValue;
|
|
|
|
/// <summary>
|
|
/// Returns the cached output if <paramref name="input"/> equals the previously stored input;
|
|
/// otherwise invokes <paramref name="mapper"/> to compute and cache a new output.
|
|
/// </summary>
|
|
/// <param name="input">The current input value.</param>
|
|
/// <param name="mapper">A function that maps the input to an output value.</param>
|
|
/// <returns>The cached or newly computed output.</returns>
|
|
public TOutput Map(TInput input, Func<TInput, TOutput> mapper)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(mapper);
|
|
|
|
if (!this._hasValue || !EqualityComparer<TInput>.Default.Equals(input, this._previousInput))
|
|
{
|
|
this._previousInput = input;
|
|
this._cachedOutput = mapper(input);
|
|
this._hasValue = true;
|
|
}
|
|
|
|
return this._cachedOutput!;
|
|
}
|
|
}
|