-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeneric-classes.ts
More file actions
50 lines (36 loc) · 1.06 KB
/
generic-classes.ts
File metadata and controls
50 lines (36 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
interface Database<T, K> {
get(id: K): T
set(id: K, value: T): void
}
interface Persistable {
saveDBtoString(): string
restoreDBfromString(storestring: string): void
}
type DBconstrainType = string | number | symbol
class InMemoryDatabase<T, K extends DBconstrainType> implements Database<T, K> {
protected db: Record<K, T> = {} as Record<K, T>
get(id: K): T {
return this.db[id]
}
set(id: K, value: T): void {
this.db[id] = value
}
}
// const myDb = new InMemoryDatabase()
class PersistableDatabase<T, K extends DBconstrainType> extends InMemoryDatabase<T, K> implements Persistable {
saveDBtoString(): string {
return JSON.stringify(this.db)
}
restoreDBfromString(storestring: string): void {
this.db = JSON.parse(storestring)
}
}
const myDb = new PersistableDatabase<number, string>()
const myDb2 = new PersistableDatabase()
myDb.set('id1', 15)
console.log(myDb.get('id1'))
const savedDB = myDb.saveDBtoString()
myDb.set('id1', 25)
console.log(myDb.get('id1'))
myDb2.restoreDBfromString(savedDB)
console.log(myDb2.get('id1'))