Spaces:
Paused
Paused
File size: 1,313 Bytes
83a59ca | 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 | export default class Bag<T> {
private items = new Map<string, Array<T>>()
serialize(): Record<string, Array<T>> {
const result: Record<string, Array<T>> = {}
this.items.forEach((value: T[], key) => {
result[key] = value
})
return result
}
static fromObject<T>(items: Record<string, Array<T>>): Bag<T> {
const result = new Bag<T>()
Object.entries(items).forEach(([key, values]) => {
result.addMany(key, values)
})
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
}
}
|