import Promise from '../promise'; import { Source } from './ReadableStream'; import ReadableStreamController from './ReadableStreamController'; const resolved = Promise.resolve(); /** * A seekable array source */ export default class ArraySource implements Source { // current seek position in the data array currentPosition: number; // shallow copy of data array passed to constructor data: Array; constructor(data: Array) { this.currentPosition = 0; this.data = []; if (data && data.length) { this.data = this.data.concat(data); } } seek(controller: ReadableStreamController, position: number): Promise { if (position >= this.data.length || position < 0) { let error = new Error('Invalid seek position: ' + position); controller.error(error); return Promise.reject(error); } this.currentPosition = position; return Promise.resolve(this.currentPosition); } start(controller: ReadableStreamController): Promise { return resolved; } pull(controller: ReadableStreamController): Promise { if (this.currentPosition >= this.data.length) { controller.close(); } else { this.currentPosition += 1; controller.enqueue(this.data[this.currentPosition - 1]); } return resolved; } cancel(reason?: any): Promise { return resolved; } }