Hari 29: Mini Proyek — Type-Safe CRUD
90 min
Last updated 09 Apr 2026
Mini Proyek: Type-Safe In-Memory Database
interface Entity { id: number }
class InMemoryDB {
private store: Map = new Map();
private nextId = 1;
insert(data: Omit): T {
const item = { id: this.nextId++, ...data } as T;
this.store.set(item.id, item);
return item;
}
findById(id: number): T | undefined {
return this.store.get(id);
}
findAll(predicate?: (item: T) => boolean): T[] {
const all = [...this.store.values()];
return predicate ? all.filter(predicate) : all;
}
update(id: number, data: Partial>): T | undefined {
const item = this.store.get(id);
if (!item) return undefined;
const updated = { ...item, ...data };
this.store.set(id, updated);
return updated;
}
delete(id: number): boolean {
return this.store.delete(id);
}
get count(): number { return this.store.size; }
}
interface Mahasiswa extends Entity {
nama: string;
jurusan: string;
ipk: number;
aktif: boolean;
}
const db = new InMemoryDB();
db.insert({ nama: "Budi", jurusan: "Informatika", ipk: 3.75, aktif: true });
db.insert({ nama: "Ani", jurusan: "Sistem Informasi", ipk: 3.50, aktif: true });
db.insert({ nama: "Cici", jurusan: "Informatika", ipk: 3.90, aktif: false });
const informatika = db.findAll(m => m.jurusan === "Informatika" && m.aktif);
console.log(`Informatika aktif: ${informatika.map(m => m.nama).join(", ")}`);
💡
Notice: Setelah delete Keyboard, db.count = 3. Stok rendah < 10: Laptop(5), Mouse(update→5), Monitor(3). Semua 3 produk masuk stok rendah.
Assignment
Implementasikan InMemoryDB untuk Produk {id, nama, harga, stok, kategori}. Insert 4 produk, update 1, delete 1, filter stok < 10, tampilkan.
Expected output:
Stok rendah (3 produk total):
Laptop: 5 unit
Mouse: 5 unit
Monitor: 3 unit
TS
index.ts
Solution
Output