forked from NdoleStudio/httpsms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbag.ts
More file actions
66 lines (55 loc) · 1.28 KB
/
bag.ts
File metadata and controls
66 lines (55 loc) · 1.28 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
export default class Bag<T> {
private items = new Map<string, Array<T>>()
serialize(): { [name: string]: Array<T> } {
const result = {}
this.items.forEach((value: T[], key) => {
// @ts-ignore
result[key] = value
})
return result
}
static fromObject<T>(items: object): Bag<T> {
const result = new Bag<T>()
Object.keys(items).forEach((key) => {
// @ts-ignore
result.addMany(key as K, items[key])
})
return result
}
add(key: string, value: T): this {
let messages: Array<T> | undefined = this.items.get(key)
if (messages === undefined) {
messages = []
}
if (!messages.includes(value)) {
messages.push(value)
}
this.items.set(key, messages)
return this
}
addMany(key: string, values: Array<T>): this {
values.forEach((value: T) => {
this.add(key, value)
})
return this
}
has(key: string): boolean {
return this.items.has(key)
}
first(key: string): T | undefined {
if (this.has(key)) {
return this.get(key)[0] ?? undefined
}
return undefined
}
get(key: string): Array<T> {
const result = this.items.get(key)
if (result === undefined) {
return []
}
return result
}
size(): number {
return this.items.size
}
}