Mastering Data Aggregation and JSON Streams with TypeScript

Introduction

Welcome to our lesson on mastering data aggregation and data streams with JSON formatting in TypeScript. In this lesson, we'll start by building a basic sales records aggregator. Leveraging TypeScript's type safety, the lesson will empower you with strong typing benefits, ensuring your data handling is robust and error-free. By the end of this session, you'll be able to manage and format data streams efficiently using TypeScript.

Starter Task Methods and Their Definitions

To begin, we'll implement a basic sales record aggregator. Here are the methods we'll be focusing on:

  • addSale(saleId: string, amount: number): void - Adds a sale record with a unique identifier saleId and an amount. If a sale with the same saleId already exists, it updates the amount.

  • getSale(saleId: string): number | undefined - Retrieves the sale amount associated with the saleId. If the sale does not exist, it returns undefined.

  • deleteSale(saleId: string): boolean - Deletes the sale record with the given saleId. Returns true if the sale was deleted and false if the sale does not exist.

Are these methods clear so far? Great! Let's now look at how we would implement them in TypeScript.

Starter Task Solution

Here is the complete code for the starter task:

TypeScript
class SalesAggregator {
    private sales: Record<string, number>;

    constructor() {
        this.sales = {};
    }

    addSale(saleId: string, amount: number): void {
        this.sales[saleId] = amount;
    }

    getSale(saleId: string): number | undefined {
        return this.sales[saleId];
    }

    deleteSale(saleId: string): boolean {
        if (saleId in this.sales) {
            delete this.sales[saleId];
            return true;
        }
        return false;
    }
}

// Example Usage
const aggregator = new SalesAggregator();

// Add sales
aggregator.addSale('001', 100.50);
aggregator.addSale('002', 200.75);

// Get sale
console.log(aggregator.getSale('001'));  // Output: 100.5

// Delete sale
console.log(aggregator.deleteSale('002'));  // Output: true
console.log(aggregator.getSale('002'));  // Output: undefined

Explanation:

  • The constructor method initializes a private object sales to store records.
  • The addSale method adds a new sale or updates the amount for an existing sale ID.
  • The getSale method retrieves the amount for a given sale ID or returns undefined if it does not exist.
  • The deleteSale method removes the sale record for the given sale ID or returns false if the sale does not exist.

With the basic aggregator implemented, let's extend it with more advanced functionalities.

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