Exercise: Building a Generic Data Store
Build a flexible, type-safe, and reusable DataStore class using generics, constraints, and composition techniques.
We'll cover the following...
In this challenge, we’re going to put everything from this chapter into action: classes, generics, constraints, method typing, and reusable patterns.
The goal is to implement a class called DataStore<T> that can safely store, retrieve, and manage typed items by ID. We’ll support optional item transformation at insertion time. We’ll also build a subclass to prevent mutation, and demonstrate all usage patterns with clear test code.
Requirements
Implement the following:
There should be a generic class
DataStore<T>whereTmust have anid: stringproperty.Store items in a
Record<string, T>.Add the following methods:
addItem(id: string, item: T): voidremoveItem(id: string): booleangetItem(id: string): T | undefined
Support an optional transformer function
(item: T) => Tpassed via constructor.This function should preprocess items before they’re stored.
Add a static method
fromArray<U>(items: U[], transformer?: (item: U) => U): DataStore<U>for bulk creation.Create a
ReadonlyStore<T>subclass that throws an error whenaddItemorremoveItemis called.
Good luck!