Introduction: Understanding Data Streams

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

Representing Data Streams in JavaScript

In JavaScript, data streams are commonly mirrored as arrays. JavaScript also facilitates additional data structures like objects and sets.

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

class DataStream {
    constructor(data) {
        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:

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

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

class DataStream {
    constructor(data) {
        this.data = data;
    }

    get(i) {
        return this.data[i];
    }
}

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

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). Please note that JavaScript does not support indexing with negative indexes, so stream.get(-1) returns undefined.

Slicing - A Useful Technique

Fetching a range of elements rather than a single one is facilitated by slicing. A slice data.slice(i, j) crafts a new array containing elements from position i (inclusive) to j (exclusive) in the data stream. We introduce a slice() method to support slicing:

class DataStream {
    constructor(data) {
        this.data = data;
    }

    get(i) {
        return this.data[i];
    }

    slice(i, j) {
        return this.data.slice(i, j);
    }
}

Here's a quick usage example:

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

console.log(stream.slice(1, 3));  // It prints: [{ id: 2, value: 200 }, { id: 3, value: 300 }]
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