initial commit

This commit is contained in:
Robin Chappatte
2024-05-21 16:10:08 +02:00
commit 5c36b2f7bc
4 changed files with 139 additions and 0 deletions

45
table.ts Normal file
View File

@@ -0,0 +1,45 @@
export type Entry = { id: number };
export class Table<TableEntry extends Entry> {
entries: TableEntry[] = [];
autoIncrementId: number = 1;
constructor(private saveCallback: () => Promise<void>) {}
private generateId(): number {
return this.autoIncrementId++;
}
async insert(record: Omit<TableEntry, "id">) {
const recordWithId = { ...record, id: this.generateId() } as TableEntry;
this.entries.push(recordWithId);
await this.saveCallback();
return recordWithId;
}
select(predicate: (entry: TableEntry) => boolean): TableEntry[] {
return this.entries.filter(predicate);
}
async update(
predicate: (entry: TableEntry) => boolean,
updateFn: (entry: TableEntry) => void,
) {
const updated: TableEntry[] = [];
this.entries.forEach((record) => {
if (predicate(record)) {
updateFn(record);
updated.push(record);
}
});
await this.saveCallback();
return updated;
}
async delete(predicate: (entry: TableEntry) => boolean) {
const deletedEntries = this.entries.filter(predicate);
this.entries = this.entries.filter((record) => !predicate(record));
await this.saveCallback();
return deletedEntries;
}
}