Home > Software engineering >  Collection with capacity and able to drop head/ drop oldest
Collection with capacity and able to drop head/ drop oldest

Time:10-23

I'm looking for a collection which creates a window of X elements, so that I can apply formulas on, e.g. Simple moving average, Exponential Moving average, etc.

Something like a queue with capacity of loopback period and when it gets full, then we drop head / drop oldest element, so we keep the most up to date ones.

Perhaps Channels<T> is suitable here? I pretty much added comments to the code.

var subResult = await _socketClient.SpotStreams.SubscribeToTradeUpdatesAsync(symbols, data =>
    {
        var trade = new Trade(data.Timestamp, data.Data.Symbol, data.Data.Price, data.Data.Quantity);

        // TODO: collection.Add(trade);
        // TODO: if (collection.Count == loopback) { signal = ... calcs ...; collection.Remove(oldest); };

        publisher.Publish(trade);
    }, stoppingToken);

CodePudding user response:

Channel<T> should work fine. If you create a bounded channel, you can specify how the channel behaves when it is full.

Pretty much any other collection you'd need to write yourself, which I have done in the pre-channels world. These days I'd just use a channel, though.

  • Related