Understanding Data Streams with TypeScript

Introduction: Understanding Data Streams

Warm greetings! This lesson introduces data streams, which are essentially continuous datasets. Think of a weather station or gaming application gathering data per second — both generate data streams! We will master handling these data streams using TypeScript, learning to access elements, slice segments, and convert these streams into strings for easier handling.

Representing Data Streams in TypeScript

In TypeScript, data streams can be represented using arrays, with additional TypeScript features like type annotations that improve code readability and robustness.

Consider a straightforward TypeScript class named DataStream. This class encapsulates operations related to data streams in our program:

TypeScript
type DataElement = { id: number, value: number };

class DataStream {
    data: DataElement[];

    constructor(data: DataElement[]) {
        this.data = data;
    }
}

To use it, we create a sample data stream as an instance of our DataStream class, where each element is an object of type DataElement with two properties, id and value:

TypeScript
const stream = new DataStream([
    { id: 1, value: 100 },
    { id: 2, value: 200 },
    { id: 3, value: 300 },
    { id: 4, value: 400 }
]);

Accessing Elements - A Key Operation

To examine individual elements of a data stream, we use indexing. The get() method we introduce below fetches the i-th element from the data stream:

TypeScript
type DataElement = { id: number, value: number };

class DataStream {
    data: DataElement[];

    constructor(data: DataElement[]) {
        this.data = data;
    }

    get(i: number): DataElement | undefined {
        return this.data[i];
    }
}

Here, we can see the get() method in action:

TypeScript
const stream = new DataStream([
    { id: 1, value: 100 },
    { id: 2, value: 200 },
    { id: 3, value: 300 },
    { id: 4, value: 400 }
]);

console.log(stream.get(2));  // It prints: { id: 3, value: 300 }
console.log(stream.get(-1)); // It prints: undefined

In essence, stream.get(2) fetched us { id: 3, value: 300 } — the third element (since indexing starts from 0). Remember that TypeScript does not support indexing with negative indexes, so stream.get(-1) returns undefined.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal