UNPKG

@tvkitchen/countertop

Version:

The entry point for developers who want to set up a TV Kitchen.

91 lines (90 loc) 2.89 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PayloadArray = void 0; const errors_1 = require("../errors"); const sortedArray_1 = require("../tools/utils/sortedArray"); const Payload_1 = require("./Payload"); class PayloadArray { constructor(payloads = []) { this.payloads = []; payloads.forEach((payload) => this.insert(payload)); } length() { return this.payloads.length; } /** * Insert a Payload into the PayloadArray while maintaining position order. */ insert(payload) { if (!(payload instanceof Payload_1.Payload)) { throw new errors_1.ValidationError('Invalid payload'); } const index = this.indexOfPosition(payload.position); this.payloads.splice(index, 0, payload); return this; } /** * Remove all payloads from the PayloadArray. */ empty() { this.payloads.length = 0; return this; } /** * Find the index to which a payload with a given position would be inserted. */ indexOfPosition(position, returnHighest = false) { return (0, sortedArray_1.sortedIndexBy)(this.payloads, position, (payload) => payload.position, returnHighest); } /** * Create a new PayloadArray containing only Payloads of the specified types. */ filterByTypes(types) { const filteredPayloads = this.payloads.filter((payload) => types.includes(payload.type)); return new PayloadArray(filteredPayloads); } /** * Create a new PayloadArray containing only Payloads of the specified type. */ filterByType(type) { return this.filterByTypes([type]); } /** * Create a new PayloadArray containing only Payloads that exist within a specified duration. */ filterByPosition(start, end) { const left = this.indexOfPosition(start); const right = end === undefined ? this.payloads.length : this.indexOfPosition(end, true); const filteredPayloads = this.payloads.slice(left, right); return new PayloadArray(filteredPayloads); } /** * Copy the content of the PayloadArray to a vanilla Array. */ toArray() { return [...this.payloads]; } /** * Get the earliest position represented in this PayloadArray. */ getPosition() { return this.payloads[0].position; } /** * Get the origin timestamp of this PayloadArray. */ getOrigin() { return this.payloads[0].origin; } /** * Get the duration represented by the payloads in this PayloadArray. */ getDuration() { const first = this.payloads[0]; const [last] = this.payloads.slice(-1); return last.position - first.position + last.duration; } } exports.PayloadArray = PayloadArray;