"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.takeLast = void 0;
const empty_js_1 = require("../observable/empty.js");
const Observable_js_1 = require("../Observable.js");
function takeLast(count) {
    return count <= 0
        ? () => empty_js_1.EMPTY
        : (source) => new Observable_js_1.Observable((destination) => {
            let ring = new Array(count);
            let counter = 0;
            source.subscribe((0, Observable_js_1.operate)({
                destination,
                next: (value) => {
                    ring[counter++ % count] = value;
                },
                complete: () => {
                    const start = count <= counter ? counter : 0;
                    const total = Math.min(count, counter);
                    for (let n = 0; n < total; n++) {
                        destination.next(ring[(start + n) % count]);
                    }
                    destination.complete();
                },
                finalize: () => {
                    ring = null;
                },
            }));
        });
}
exports.takeLast = takeLast;