Topic Overview

Welcome to our exploration of sorted maps using custom classes and comparators in TypeScript. In today's lesson, we'll learn how to use custom classes as keys in sorted maps. This approach enhances data organization and access. While TypeScript does not possess a built-in sorted map, we can use the @datastructures-js/binary-search-tree library to achieve this functionality, leveraging TypeScript’s robust type system to enforce type safety and clarity.

Introduction to Custom Classes in TypeScript

Custom classes enable us to create objects that align with our data requirements — for instance, a Person class for employee information or a Book class for a library database. In TypeScript, classes not only serve as blueprints for creating objects but also offer type annotations for ensuring type safety.

Consider this simple class, for example:

TypeScript
class Person {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
}

let person = new Person("John Doe", 30);
console.log(person.name);  // Outputs "John Doe"
console.log(person.age);   // Outputs 30
Using Custom Classes with Binary Search Trees

Using custom classes helps organize complex multivariate data. We will use the @datastructures-js/binary-search-tree library to maintain our data in a sorted order. Below is an example of how to use comparators to dictate the order when using custom classes with this binary search tree:

import { BinarySearchTree } from '@datastructures-js/binary-search-tree';

class Person {
    name: string;
    age: number;
    occupation: string;

    constructor(name: string, age: number, occupation: string) {
        this.name = name;
        this.age = age;
        this.occupation = occupation;
    }

    compare(other: Person): number {
        return this.age - other.age;
    }

    toString(): string {
        return `${this.name} is a ${this.occupation}`;
    }
}

let tree = new BinarySearchTree<Person>((a, b) => a.compare(b));

let john = new Person("John", 30, "Programmer");
let alice = new Person("Alice", 25, "Designer");

tree.insert(john);
tree.insert(alice);

// In-order traversal to print sorted entries
tree.traverseInOrder((node) => {
    console.log(node.getValue().toString());
});
// Output:
// Alice is a Designer
// John is a Programmer

In-order traversal is a method of traversing a binary search tree where nodes are visited in ascending order, ensuring sequential data access.

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