//
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ Copyright (c) JP Dillingham.
// │
// │ This program is free software: you can redistribute it and/or modify
// │ it under the terms of the GNU Affero General Public License as published
// │ by the Free Software Foundation, version 3.
// │
// │ This program is distributed in the hope that it will be useful,
// │ but WITHOUT ANY WARRANTY; without even the implied warranty of
// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// │ GNU Affero General Public License for more details.
// │
// │ You should have received a copy of the GNU Affero General Public License
// │ along with this program. If not, see https://www.gnu.org/licenses/.
// │
// │ This program is distributed with Additional Terms pursuant to Section 7
// │ of the AGPLv3. See the LICENSE file in the root directory of this
// │ project for the complete terms and conditions.
// │
// │ https://slskd.org
// │
// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
// │ SPDX-FileCopyrightText: JP Dillingham
// │ SPDX-License-Identifier: AGPL-3.0-only
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
//
using System;
namespace slskd
{
///
/// An exponential moving average.
///
public class ExponentialMovingAverage
{
///
/// Initializes a new instance of the class.
///
///
public ExponentialMovingAverage(double smoothingFactor)
{
SmoothingFactor = smoothingFactor;
}
///
/// Initializes a new instance of the class.
///
///
///
public ExponentialMovingAverage(double smoothingFactor, Action onUpdate = null)
: this(smoothingFactor)
{
OnUpdate = onUpdate;
}
///
/// Gets the current value.
///
public double Value { get; private set; } = 0;
///
/// Gets a value indicating whether the average has been initialized.
///
public bool Initialized { get; private set; } = false;
private double SmoothingFactor { get; }
private Action OnUpdate { get; }
///
/// Resets the value.
///
public void Reset()
{
Value = 0;
Initialized = false;
OnUpdate?.Invoke(Value);
}
///
/// Updates the average with a new value.
///
///
public void Update(double value)
{
Value = !Initialized ? value : ((value - Value) * SmoothingFactor) + Value;
Initialized = true;
OnUpdate?.Invoke(Value);
}
}
}